【问题标题】:Display data with ID matching text box value in datagridview?在datagridview中显示ID匹配文本框值的数据?
【发布时间】:2015-08-29 13:19:24
【问题描述】:

有一个名为cartdesignsizes 的表。它有一列cartkey。我在文本框中输入cartkey,然后单击按钮,我希望整行与cartkey 相对,并且我想在datagridview 中显示该行。

代码如下:

 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;

【问题讨论】:

  • 请给我一个更好的方法

标签: c# sql datagridview textbox


【解决方案1】:

您应该更改这一行(我看不到您如何编译它,因为 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 定义了一个属性,您可以使用它来添加所需的参数。

另请注意,如果您以这种方式使用适配器,则无需打开/关闭连接。这是由 Fill 调用中的适配器自动完成的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多