简体   繁体   English

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

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

i am trying to retrieve data from a column in SQL DB depending on the value of combo box in datagridview my code is : 我试图根据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();
        }
 } 

I want to put the price in dataGridView1.CurrentRow.Cells[2] 我想把价格放在dataGridView1.CurrentRow.Cells[2]

BUT i get an sqlexception everytime I choose item from the combo box 但是每次我从组合框中选择项目时,我都会得到一个sqlexception

Any help ?? 有帮助吗??

If the data type of column Name is VARCHAR, you need to wrap the value with single quotes because it's a string literal. 如果“ Name ”列的数据类型为VARCHAR,则需要使用单引号将值引起来,因为它是字符串文字。

string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name='" + _val + "'");

but the query is vulnerable with SQL Injection . 但是查询容易受到SQL Injection攻击。 Please do parameterized the query,eg. 请对查询进行参数化,例如。

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