0

Hi I want to fill a combo box with names from a table where id is the number contained in textbox.The txtPartId is populated from another page as is the name in txtPart. The error I get when I run this is "Invalid column name "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);
        }
    }
4

1 回答 1

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上有很多这样的例子。

于 2013-08-27T14:23:49.253 回答