将Id设置为文本框中包含的数字

时间:2013-08-27 14:20:11

标签: c# wpf

您好我想填充一个组合框,其名称来自一个表,其中id是文本框中包含的数字.txtPartId是从另一个页面填充的,就像txtPart中的名称一样。我运行它时得到的错误是“无效的列名称”txtPartId“

public ReList(string Str_value, string id)//declare value
    {
        InitializeComponent();
        txtPart.Text = Str_value;
        txtPartId.Text = id.ToString();
        displayRe();
    }

    private void displayRe()
    {
        try
        {
            sc.Open();
            string Query = "select * from Re where Part_PartID =txtPartId ";
            SqlCommand createCommand = new SqlCommand(Query, sc);
            SqlDataReader dr = createCommand.ExecuteReader();
            while (dr.Read())
            {
                string Name = dr.GetString(1);

                cbRe.Items.Add(Name);//Displaying a list in the Combo Box
            }
            sc.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:1)

快速而肮脏的答案是进行以下更改:

string Query = "select * from Re where Part_PartID = " + txtPartId.Text;

假设Part_PartID是一个整数。

如果是字符串,则可以使用:

string Query = string.Format("select * from Re where Part_PartID = '{0}'", txtPartId.Text);

编译器不会将txtPartId中的文本值注入您的查询字符串中。

但是,这引入了SQL注入的范围,因此我强烈建议您参数化查询。 SO上有很多例子。