链接文本框C#SQL Server

时间:2016-11-03 07:46:29

标签: c# sql-server

如何链接文本框?

场景:

TextBox_Supplier
TextBox_Address

TextBox_Supplier是自动填充功能,并且正常运行。在TextBox_Supplier中输入后,TextBox_Address会选择供应商的地址。

我的代码不起作用:

private void txb_vendor_TextChanged(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txb_address.Text))
    {
        PurCon.con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = PurCon.getcon();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name = {0}",txb_vendor.Text);

        SqlDataReader red = cmd.ExecuteReader();

        while (red.Read())
        {
            string address = red.GetString(0);
            address = txb_address.Text;
        }

        PurCon.con.Close();
    }
}

感谢您帮助我!

3 个答案:

答案 0 :(得分:2)

而不是

address = txb_address.Text;

txb_address.Text = address;

尝试使用参数化查询而不是字符串的连接。

答案 1 :(得分:0)

按照@Mohit的建议进行更改,并使用单引号包装供应商名称,因为供应商名称是字符串类型,并且在sql中字符串应该包装在单个引号中,否则将导致SQL错误

"SELECT address FROM tbl_Supplier WHERE supplier_name = '{0}'"
                                                    ----^   

答案 2 :(得分:0)

上周我已经解决了这个问题。而且我很生气喽!

textbox_Address没有改变一次,它在textbox_Supplier_TextChaged时堆叠起来。所以我把Clear()方法清除以前的输入地址。

public void AddressTbxLoad()
    {

        DBCon PurCon = new DBCon();
        PurCon.con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = PurCon2.con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name LIKE '{0}%'", cbx_vendor.Text);
        SqlDataReader red = cmd.ExecuteReader();

        while (red.Read())
        {
            string address = red.GetString(0);
            txb_address.Text = address;

        }
        PurCon.con.Close();
    }

    private void cbx_vendor_SelectedIndexChanged(object sender, EventArgs e)
    {
        txb_address.Clear();
        AddressTbxLoad();
    }

    private void Purchase_Load(object sender, EventArgs e)
    {
        VendorTbxLoad();
    }