我使用以下代码从数据库中获取名字并将其添加到文本框集合中:
String ConString = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\\Database.mdf; Integrated Security = True";
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT Lname,Fname,DDN FROM Staff", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
MyCollection.Add(reader.GetString(0));
}
TNom.AutoCompleteCustomSource = MyCollection;
con.Close();
}
自动完成功能有效,但是我想获取所选项目的ID,并用它来填充下面的datagrid视图
答案 0 :(得分:1)
这是非常的骨头,没有实现良好的封装,没有“ using”语句,需要捕获错误...也就是说,这应该是如何从中获取价值的样板在文本框中,获取该数据集的数据集并将其应用于网格:
SqlCommand cmd = new SqlCommand("select * from foo where bar = @BAR", conn);
cmd.Parameters.Add(new SqlParameter("@BAR", SqlDbType.VarChar));
cmd.Parameters[0].Value = TNom.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;