获取所选供应商名称的供应商ID(组合框值),以显示在文本框中 [英] Get the Supplier ID of selected Supplier Name (combobox value) to appear in a textbox

查看:96
本文介绍了获取所选供应商名称的供应商ID(组合框值),以显示在文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将供应商名称的供应商ID (组合框值)显示为出现在文本框中 ...此代码可以正常工作吗?

I''m trying to get the supplier id of the supplier name (combo box value) to appear in a textbox... can this code work?

string query = "select * from Supplier WHERE SupplierName = '" + cbosupplier.SelectedValue.ToString() + "'";
              SqlCommand cmd = new SqlCommand(query, cn);
              cmd.CommandText = query;

              txtsupplierno.Text = query;

推荐答案

否.

下一个问题?

您必须执行查询,并使用结果数据集-哦,请使用参数化查询.它有助于避免意外或故意损坏数据库...
试试这个:
No.

Next question?

You have to execute the query, and use the resulting dataset - Oh, and please use parameterised queries. It help avoid accidental or deliberay damage to your database...
Try this:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Id FROM Supplier WHERE SupplierName = @SN", con))
        {
        cmd.Parameters.AddWithValue("@SN", cbosupplier.SelectedValue);
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                }
            }
        }
    }


您将需要执行阅读器,读取查询结果,然后将结果保存到属性中.我看起来像这样:

You are going to need to execute a reader, read the query results, and save the results into your property. I would look something like this:

SqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
{
   txtsupplierno.Text =rdr["SupplierId"].ToString();
}



这将遍历每条记录,并将该值放入文本字​​段,覆盖最后一个值.如果您要返回多个行,这不是理想的选择,但是它可以完成工作(快速而肮脏的第一遍).

接下来,您需要考虑保护自己免受SQL注入的侵害.您永远不要将UI中的值直接传递到SQL语句中.用户可以将代码放在文本框中,以使他们可以控制您的数据库.如果您的组合框不允许输入值,那么您会更安全,但是我仍然希望看到使用参数将值插入到语句中.

这是一个很好的教程,其中包含更多信息,可以为您提供帮助:

http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03 [ ^ ]



This would loop through each record and put that value into the text field, overwriting the last value. It isn''t ideal if you are going to return more than one row but it gets the job done (quick and dirty first pass).

Next you need to think about protecting yourself against SQL injection. You should never pass a value from the UI straight into a SQL statement. The user could put code in the text box that would give them control over your database. If your combobox does not allow values to be typed in, you are safer, but I still like to see values to be inserted into statements using parameters.

Here is a good tutorial with more information that should help you out:

http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03[^]


没有使用datareader或datatable
No you use datareader or datatable


这篇关于获取所选供应商名称的供应商ID(组合框值),以显示在文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆