Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 根据c中datagridview中组合框的值从SQL server检索数据#_C#_Sql Server - Fatal编程技术网

C# 根据c中datagridview中组合框的值从SQL server检索数据#

C# 根据c中datagridview中组合框的值从SQL server检索数据#,c#,sql-server,C#,Sql Server,我试图根据datagridview中combo box的值从SQL DB中的列检索数据。我的代码是: private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs { using (SqlConnection conn = new SqlConnection("Data Source=POSSERVER\\SQLEXPRESS;Initial Catalog=ms;Integr

我试图根据datagridview中combo box的值从SQL DB中的列检索数据。我的代码是:

 private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs 
 {
        using (SqlConnection conn = new SqlConnection("Data Source=POSSERVER\\SQLEXPRESS;Initial Catalog=ms;Integrated Security=True"))
        {
            string priceselected = ("SELECT price FROM Table_1 WHERE name=" + dataGridView1.CurrentRow.Cells[0].Value.ToString());
            SqlCommand cmd = new SqlCommand(priceselected, conn);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
 } 
我想把价格放在
dataGridView1.CurrentRow.Cells[2]

但每次从组合框中选择项时,我都会得到一个sqlexception


有什么帮助吗

如果列
Name
的数据类型是VARCHAR,则需要使用单引号将值括起来,因为它是字符串文本

string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name='" + _val + "'");
但是使用
SQL注入
时,查询易受攻击。请执行参数化查询,例如

string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name=@val");
SqlCommand cmd = new SqlCommand(priceselected, conn);
cmd.Parameters.AddWithValue("@val", _val);
conn.Open();
cmd.ExecuteNonQuery();

请详细分享您的异常您得到的异常或错误是什么?组合框中的值是什么?以下是一些未来的提示:调试代码;手动运行sql命令;了解如何避免sql注入。=)非常感谢它的工作,但现在我想在dataGridView1.CurrentRow.Cells[2]上显示该值