在datagridview中显示ID匹配文本框值的数据?

Display data with ID matching text box value in datagridview?

有一个名为 cartdesignsizes 的 table。它有一列 cartkey。我在文本框中输入 cartkey,然后单击按钮,我希望整行与 cartkey 相对应,我想在数据网格视图中显示该行。

代码如下:

 private void btncartdesign_Click(object sender, EventArgs e)
        {
            {
                SqlConnection sql = new SqlConnection("Data Source=75.119.176.76;Initial Catalog=virtual-11;Persist Security Info=True;User ID=sa;Password=kornit932");
                sql.Open();
                DataTable dt = new DataTable();
                SqlDataAdapter sd = new SqlDataAdapter("select * from CartdesignSizes where cartkey=@txtcartkey", sql);
                SqlCommand cmd = new SqlCommand("select * from CartdesignSizes where CartKey=@txtcartkey", sql);
                cmd.Parameters.AddWithValue("@txtcartkey", txtcartkey.Text);
                cmd.ExecuteNonQuery();
                sd.Fill(dt);
                dataGridView.DataSource = cmd.tables[0];
                sql.Close();
                label2.Visible = true;
                label2.Text = dataGridView.Rows.Count.ToString();

            }
        }

文本框后面的代码:

DataView DV = new DataView(dbdataset);
            DV.RowFilter=String.Format("CartKey LIKE '{0}'",txtcartkey.Text);
            dataGridView.DataSource = DV;

您应该更改这一行(我看不出您如何编译它,因为 SqlCommand 没有 tables 属性

dataGridView.DataSource = cmd.tables[0];

dataGridView.DataSource = dt;

但是您的代码应该更改以删除一些无用的重复代码并引入 using 语句以更好地处理此查询中涉及的对象的处置

private void btncartdesign_Click(object sender, EventArgs e)
{
    string sqlText = @"select * from CartdesignSizes 
                       where cartkey=@txtcartkey";
    DataTable dt = new DataTable();
    using(SqlConnection sql = new SqlConnection(.....))
    using(SqlDataAdapter sd = new SqlDataAdapter(sqlText, sql))
    {
        sd.SelectCommand.Parameters.Add("@txtcartkey", 
                      SqlDbType.NVarChar).Value = txtcartkey.Text;
        sd.Fill(dt);
        dataGridView.DataSource = dt;
        label2.Visible = true;
        label2.Text = dataGridView.Rows.Count.ToString();
    }
}

这样,所涉及的两个一次性对象(连接和适配器)被正确地放置在 using 块的末尾。无需创建单独的命令,因为适配器已经为 SelectCommand 定义了 属性,您可以使用它来添加所需的参数。

另请注意,如果您以这种方式使用适配器,则不需要 open/close 连接。这是由 Fill 调用中的适配器自动完成的。