通过关闭表单按钮方法以编程方式获取组合框的值

时间:2018-09-05 18:41:50

标签: c# winforms

我有一个自动创建的按钮,因此在方法事件中,我可以轻松地按以下方式调用值:

deleted_at

但是现在我有一个类似按钮方法的封闭表单:

private void ComboEmployee_SelectedValueChanged(object sender, EventArgs e)
        {
          var employeeComboBox = sender as ComboBox;
          var currentTextCombo = employeeComboBox.Text
        }

问题是 private void btnClose_Click(object sender, EventArgs e) { var employeeComboBox = sender as ComboBox; var currentEmployeeComboBoxText = employeeComboBox.Text; SaveTechniciansToNotify(currentEmployeeComboBoxText); this.Close(); } 总是为null,它没有获取comboBox的当前值,如何通过这种方法获取当前combobox的值?问候

2 个答案:

答案 0 :(得分:1)

一个易于实现的解决方案是在表单类内部创建一个字符串类型的私有字段,并将其传递给您的方法SaveTechniciansToNotify:

//Make sure this is part of your class and not local to a method
private string _comboVal;

//Set your private field inside the SelectedValueChanged event of your combo box
private void ComboEmployee_SelectedValueChanged(object sender, EventArgs e)
{
     var employeeComboBox = sender as ComboBox;
     _comboVal = employeeComboBox.Text
}

//Finally Pass private field value to method SaveTechniciansToNotify
 private void btnClose_Click(object sender, EventArgs e)
 {
            //pass in your private field value
            SaveTechniciansToNotify(_comboVal);
            this.Close();
 }

答案 1 :(得分:0)

您遇到了这个问题,因为您的 btnClose_Click 方法中的对象发件人不是组合框(按钮 btnClose 的可能性更大em>)。

根据您的 ComboEmployee_SelectedValueChanged 事件处理程序的外观,您的ComboBox的名称为 ComboEmployee

您可以通过按如下所示按名称引用来在 btnClose_Click 处理程序中访问ComboBox的Text属性:

private void btnClose_Click(object sender, EventArgs e)
{
    var currentEmployeeComboBoxText = ComboEmployee.Text;
    SaveTechniciansToNotify(currentEmployeeComboBoxText);
    this.Close();
}