繁体   English   中英

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

[英]retrieve data from SQL server depending on value of combo box in datagridview in c#

我试图根据datagridview中组合框的值从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 Injection攻击。 请对查询进行参数化,例如。

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM