0

我有一个带有数据绑定组合框的表单,dropstyle 设置为下拉列表,因此用户可以在组合框中键入。

我的问题是,当用户在组合框中键入并且键入的值与绑定到组合框的值之一匹配时,即使我也尝试过,它也不会更改 selectedindex。相反,它将选定的索引设置为 -1(因此选定的值为空)。

任何人都可以帮忙吗?这是我的代码(我的尝试之一,我尝试了其他方法但没有帮助)。

private void setCombo()
{
        comboFromOther.DisplayMember = "tbl10_KupaID";
        comboFromOther.ValueMember = "tbl10_KupaID";
        comboFromOther.DataSource = dsKupotGemel.Tables[0];
}

private void comboToOther_TextChanged(object sender, EventArgs e)
{
        comboDetail = changedComboText(2, comboToOther.Text);
        textToOther.Text = comboDetail[0];
        if (comboDetail[0] == "")
        {

        }
        else
        {
            comboToOther.SelectedIndex = System.Int32.Parse(comboDetail[1]);
            comboToOther.SelectedValue = System.Int32.Parse(comboDetail[2]);
        } 
    }

    private string[] changedComboText(int iComboType, string comboString)
    {
        if (groupCalculate.Visible == true)
        {
            groupCalculate.Visible = false;
        }
        string[] kupaDetail = new string[3];
        kupaDetail[0] = "";
        kupaDetail[1] = "";
        kupaDetail[2] = "";
        for (int i = 0; i <= dsKupotGemel.Tables[0].Rows.Count - 1; i++)
        {
           if (comboString == dsKupotGemel.Tables[0].Rows[i][0].ToString())
           {
                 kupaDetail[0] = dsKupotGemel.Tables[0].Rows[i][1].ToString();
                 kupaDetail[1] = i.ToString();
                 kupaDetail[2] = comboString;
                 break;
           }
           else
           {

           }
        }
   return kupaDetail;
}
4

1 回答 1

0

也许您的代码中有错误?

这是一个工作示例:

// Fields
private const string NameColumn = "Name";
private const string IdColumn = "ID";

private DataTable table;

接下来,初始化

// Data source
table = new DataTable("SomeTable");
table.Columns.Add(NameColumn, typeof(string));
table.Columns.Add(IdColumn, typeof(int));

table.Rows.Add("First", 1);
table.Rows.Add("Second", 2);
table.Rows.Add("Third", 3);
table.Rows.Add("Last", 4);

// Combo box:
this.comboBox1.DisplayMember = NameColumn;
this.comboBox1.ValueMember = IdColumn;
this.comboBox1.DataSource = table;
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
this.comboBox1.TextChanged += comboBox1_TextChanged;
this.comboBox1.SelectedIndexChanged += this.comboBox1_SelectedIndexChanged;

事件处理程序 - TextChanged:

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    for (int i = 0; i < table.Rows.Count; i++)
    {
        if (table.Rows[i][NameColumn].ToString() == this.comboBox1.Text)
        {
            this.comboBox1.SelectedValue = table.Rows[i][IdColumn];
            break;
        }
    }
}

事件处理程序 - SelectedIndexChanged:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Do here what is required
}

使用此代码,只要用户在组合框中键入项目的全名,就会通过 TextChanged 调用 SelectedIndexChanged。

还有诸如AutoCompleteModeAutoCompleteSource之类的东西。不知道它们适合您的应用程序的位置。

于 2013-01-01T20:13:29.780 回答