有一个名为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;
文本框后面的代码:
<security-constraint>
<web-resource-collection>
<web-resource-name>private</web-resource-name>
<url-pattern>/private/*</url-pattern>
<http-method>OPTIONS</http-method>
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>
AppAdmins
</role-name>
<role-name>
AppUsers
</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>AppAdmins</role-name>
</security-role>
<security-role>
<role-name>AppUsers</role-name>
</security-role>
答案 0 :(得分:1)
您应该更改此行(我无法看到您如何编译它,因为SqlCommand没有表属性
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();
}
}
通过这种方式,所涉及的两个一次性物体(连接和适配器)被正确地设置在使用块的末端。无需创建单独的命令,因为适配器已经为SelectCommand定义了属性,您可以使用它来添加所需的参数。
另请注意,如果您以这种方式使用适配器,则无需打开/关闭连接。这是由填充调用内的适配器自动完成的。