我有一个带有数据绑定组合框的表单,dropstyle设置为下拉列表,因此用户可以键入组合框。
我的问题是,当用户键入组合框并且键入的值匹配绑定到组合框的其中一个值时,即使我也尝试过,它也不会更改selectedindex。相反,它将所选索引设置为-1(因此所选值为null)。
有人可以帮忙吗?这是我的代码(我的尝试之一,我尝试了其他方法,但没有帮助)。
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;
}
答案 0 :(得分: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。
还有AutoCompleteMode,AutoCompleteSource之类的东西。不知道它们适合您的应用程序。