【问题标题】:ShowDialog() does not wait for inputShowDialog() 不等待输入
【发布时间】:2013-09-17 10:47:55
【问题描述】:

也许这个问题对某些人来说很容易,但它困扰着我。

我正在寻找的行为是: - 当我选择一个菜单项时,会出现一个对话框; - 选择对话框后,根据所做的选择呈现一个新的表单

这是代码:

        this.panel1.Controls.Clear();
        if (this.childForm != null)
        {
            this.childForm.Dispose();
            this.childForm = null;
        }

        using (var selectionForm = new SelectTransaction())
        {
            var result = selectionForm.ShowDialog();
            childForm = new TransactionForm(selectionForm.transactionName);
            childForm.TopLevel = false;
            this.panel1.Controls.Add(childForm);
            childForm.Location = new Point(0, 0);
            childForm.Show();
        }  

代码通常按我的意愿工作。但有时,主要是在连续两次进行选择时,ShowDialog() 不会等待我的输入。它会显示表单。

我尝试自己创建和处置选择对象(而不是使用using),但出现了同样的问题。

对话结果以SelectTransaction形式设置。在那里我有一个combobox,当我选择一个项目时,我返回结果。

public partial class SelectTransaction : Form
{
    public string transactionName;

    public SelectTransaction()
    {
        InitializeComponent();

        // The data set is retrieving from a database

        selectTransactionComboBox.Text = " - SELECT TRANSACTION - ";
        selectTransactionComboBox.Items.Clear();
        for (int i = 0; i < dataSet.Tables["TransactionInfo"].Rows.Count; i++)
        {      
            selectTransactionComboBox.Items.Add(dataSet.Tables["TransactionInfo"].Rows[i].ItemArray.GetValue(0).ToString());
         }  
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.transactionName = selectTransactionComboBox.Items[selectTransactionComboBox.SelectedIndex].ToString();
        this.Close();
    }
}

谁能告诉我我做错了什么?

【问题讨论】:

  • 澄清您的要求:您说有时selectionForm.ShowDialog() 会立即返回?
  • 很难从这段代码中找到bug。但作为替代方案,您可以在调用 showdialog 之前在 selectionform 的关闭事件中添加必须在 selectionform 关闭后执行的代码。
  • @CoralDoe:在这种情况下,它很可能来自SelectTransaction 实现。例如,您在哪里调用 Close() 或设置 DialogResult ?还有你有没有将DefaultValue 设置为某些东西的按钮?
  • SelectTransaction 包含一个combobox。在indexchanged 事件中,我得到选择并调用Close()。
  • @CoralDoe:我认为SelectedIndexChanged 是在您以编程方式设置SelectedIndex 或SelectedItem 时引发的,您是否设置其中之一?

标签: c# winforms desktop-application showdialog


【解决方案1】:

有时 SelectedIndexChanged-Event 会在您填充组合框时触发。而是使用 SelectionChangeCommitted-Event http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx

或另一种解决方案:不要在表单中添加事件监听器,只需在填充组合框后添加它(在完成 For-Loop 之后)

selectTransactionComboBox.SelectedIndexChanged += comboBox1_SelectedIndexChanged

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多