在WinForms的组合框中插入项目

本文关键字:插入项目 组合 WinForms | 更新日期: 2023-09-27 18:21:59

在我的程序中,我有两个下拉列表组合框。只有在选择了第一个组合框中的项目后,我才想将项目添加到第二个组合框。

到目前为止,我有这个:

InitializeComponent();
comboBox1.Items.Add("Category1");
comboBox1.Items.Add("Category2");
comboBox1.Items.Add("Category3");
comboBox1.SelectedValueChanged += new EventHandler(comboBox1_TextChanged);
private void comboBox1_TextChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedText.Equals("Category 1"))
    {
        DataTable cat = dataTableAdapter.GetByCategory("category1");
        foreach (DataRow row in cat.Rows)
        {
            comboBox2.Items.Add(row.ItemArray[1]);
        }
    }
}

在WinForms的组合框中插入项目

MSDN中关于使用ComboBox.SelectedText和DropDownList样式的说明:

If DropDownStyle is set to DropDownList, the return value is an empty string ("").

因此,您可能不得不使用SelectedIndex或SelectedItem属性(或者将ComboBox的样式更改为其他类型之一)。

更改

if (comboBox1.SelectedText.Equals("Category 1"))

if (comboBox1.SelectedItem.ToString().Equals("Category1"))