选择值在组合框中选择的任何项目给我null为什么

时间:2017-01-24 14:48:40

标签: .net winforms c#-4.0 combobox

问题

组合框中任何项目的选定值都为null,为什么

详情

我在Windows窗体c#visual studio 2015中工作

我从excel表2007获取组合框的数据

excel表有两列

MemberId表示组合框的值

MemberName表示组合框的文本

 var fileName = string.Format("{0}\\Book3105", Directory.GetCurrentDirectory());
        var connection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};Mode=ReadWrite;Extended Properties=Excel 12.0 Xml;", fileName);

        OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + "D:\\Book3105.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES\"");
        OleDbConnection con = new OleDbConnection(connection);

        try
        {
            con.Open();
            str = "select * from [sheet2$]";
            com = new OleDbCommand(str, con);
            oledbda = new OleDbDataAdapter(com);
            ds = new DataSet();
            oledbda.Fill(ds, "[sheet2$]");
            con.Close();

            dt = ds.Tables["[sheet2$]"];
            int i = 0;


            for (i = 0; i <= dt.Rows.Count - 1; i++)
            {
                comboBox4.Items.Insert(0, "select member");
                comboBox4.SelectedIndex = 0;
                comboBox4.Items.Add(dt.Rows[i].ItemArray[1]);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

在按钮下调试此行时,为null

当选择组合框中的任何项目时,

和消息框显示给我。

private void buttontest_Click(object sender, EventArgs e)
        {

           if(Convert.ToInt32(comboBox4.SelectedValue)==0)
            {
                MessageBox.Show("wrong value");

            }

        }

1 个答案:

答案 0 :(得分:0)

在填充组合框后设置组合框的ValueMemberDisplayMember。确保组合框的属性设置为DropDownStyle: DropDownList

for (i = 0; i <= dt.Rows.Count - 1; i++)
{
     comboBox4.Items.Insert(0, "select member");
     comboBox4.SelectedIndex = 0;
     comboBox4.Items.Add(dt.Rows[i].ItemArray[1]);
}

comboBox4.ValueMember = "MemberId";
comboBox4.DisplayMember = "MemberName";

然后在button_click事件中检查SelectedItem值,如

if(Convert.ToInt32(((KeyValuePair<string,string >)comboBox4.SelectedItem).Key) == 0)
{
     MessageBox.Show("wrong value");
}