【问题标题】:C# get database id of selected item from auto complete text boxC#从自动完成文本框中获取所选项目的数据库ID
【发布时间】:2019-05-19 01:08:25
【问题描述】:

我使用此代码从数据库中获取名字并将其添加到文本框集合中:

    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 并使用它来填充下面的数据网格视图

【问题讨论】:

    标签: c# sql autocomplete windowsformshost


    【解决方案1】:

    这是 非常 简单的骨架,没有进行良好的封装,没有“使用”语句,需要错误捕获......也就是说,它应该是您如何获取价值的样板文本框,取回一个数据集并将其应用于网格:

    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;
    

    【讨论】:

      猜你喜欢
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      相关资源
      最近更新 更多