需求:
每输入字符时combobox.text追加字符,读取数据库并弹出下拉列表,但是text不要不要不要自动选择下拉列表中的项,并且不能清空text,datasouce必须为datatable,因为最后需要得到选取项的(DataRowView)SelectItem.Row。
遇到的问题:
新手问题多,每次droppeddown =true时,都会清空text,并自动选择了第一项,使用textupdate事件,并且text为空或者焦点移动时,因为下拉列表会清空,如果不在开始时进行droppeddown = false,会报index不能为0的错,求大神帮解决一下,以下贴出代码。
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
this.comboBox1.DroppedDown = false;
string s = comboBox1.Text;
int newcount = s.Length - i.Length;
i += s.Substring(i.Length, newcount);
comboBox1.DataSource = null;
DataSet ds = new DataSet();
string conntext = "Uid=sa; pwd=sa; database=XZ; server=localhost";
SqlConnection conn = new SqlConnection(conntext);
string sql = "select * from Book where BookName like '%" + comboBox1.Text + "%'";
if (comboBox1.Text != string.Empty)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
ds.Load(dr, LoadOption.OverwriteChanges, "book");
if (ds.Tables["book"].Rows.Count > 0)
{
this.comboBox1.DataSource = ds.Tables[0];
this.comboBox1.DisplayMember = "bookname";
//this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//this.comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
this.comboBox1.DroppedDown = true;
//this.comboBox1.DataSource = ds.Tables["book"];
//comboBox1.SelectedIndex = -1;
}
}
this.comboBox1.Text = i;
conn.Close();
comboBox1.SelectionStart = comboBox1.Text.Length;
Cursor.Current = Cursors.Default;
}