我正在尝试在C#中实现一个自动完成的组合框。当我将组合框下拉属性设置为“下拉”时,我可以这样做。但是无法得到结果当下拉属性设置为'删除列表'。请帮我解决这个问题。
这是我的代码:
var connection=new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\xxx.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
var command=new SqlCommand("SELECT model FROM vehicle",connection);
var adapter=new SqlDataAdapter(command);
var ds = new DataSet();
adapter.Fill(ds);
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
int i = 0;
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
col.Add(ds.Tables[0].Rows[i]["model"].ToString());
}
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
comboBox1.AutoCompleteCustomSource = col;
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
答案 0 :(得分:0)
您可以尝试这样的事情
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection combData = new AutoCompleteStringCollection();
getData(combData);
comboBox1.AutoCompleteCustomSource = combData;
}
private void getData(AutoCompleteStringCollection dataCollection)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
connetionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\xxx.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sql = "SELECT model FROM vehicle";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
foreach (DataRow row in ds.Tables[0].Rows)
{
dataCollection.Add(row[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}