C#从自动完成文本框中获取所选项目的数据库id
我使用以下代码从数据库中获取名字并将其添加到textbox集合:C#从自动完成文本框中获取所选项目的数据库id,c#,sql,autocomplete,windowsformshost,C#,Sql,Autocomplete,Windowsformshost,我使用以下代码从数据库中获取名字并将其添加到textbox集合: String ConString = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\\Database.mdf; Integrated Security = True"; using (SqlConnection con = new SqlConnection(ConString)) {
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视图这是非常简单的,没有很好的封装,没有“使用”语句,需要错误捕获。。。这就是说,它应该是一个样板,说明如何从文本框中获取值,获取数据集并将其应用于网格:
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;