【问题标题】:selected value to any item selected in combobox give me null why组合框中选择的任何项目的选定值给我 null 为什么
【发布时间】:2017-01-24 14:48:40
【问题描述】:

问题

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

详情

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

我从 excel sheet 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");

            }

        }

【问题讨论】:

    标签: .net winforms c#-4.0 combobox


    【解决方案1】:

    填充组合框后,为组合框设置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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 2020-05-23
      • 2015-01-23
      相关资源
      最近更新 更多