在selectedIndexChanged事件上访问comboBox的值

时间:2018-09-07 23:30:29

标签: c# winforms

我有一个comboBoxSelectedItemChanged事件。所以我想提取所选项目的值,例如:

private void cboCustomerType_SelectedIndexChanged(object sender, EventArgs e)
{
    var db = new SQLConnMgr();

    ComboBox cmb = (ComboBox)sender;
    var comboSelectedValue = cmb.SelectedItem;
}

问题是我想要的价值在cmb.SelectedItem.Row.ItemArray[1]enter image description here

但是我无法访问cmb.SelectedItem.Row。为什么我做不到这么简单:cmb.SelectedItem.Row.ItemArray[1]?问候

2 个答案:

答案 0 :(得分:0)

您选择的项目类型是DataRowView,因此您需要将SelectedItem强制转换为该类型:

private void cboCustomerType_SelectedIndexChanged(object sender, EventArgs e)
{
    // A combobox with nothing selected will have a SelectedIndex of -1
    if (cboCustomerType.SelectedIndex > -1)
    {
        // Cast SelectedItem to DataRowView
        DataRowView item = cboCustomerType.SelectedItem as DataRowView;

        if (item != null)
        {
            // Access the data in column 1 of the selected row
            string value = item[1].ToString();
        }
    }
}

答案 1 :(得分:0)

我相信您正在将组合框与DataSet绑定。因此,您可以这样做:

DataRow dataRow = dataSet.Select(string.Format("FieldName = '{0}'",     ComboBox.SelectedValue.ToString()))[0];

if (ComboxBox.SelectedValue != null)
{

// can use fields like 

String text = dataRow[“fieldName”].ToString();
}

else
{ //something wrong
}
}