从列表框和不同的数据源中选择项目 [英] Select items from listbox and different datasources

查看:56
本文介绍了从列表框和不同的数据源中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试实现一个简单的webform(创建你自己的产品),所以我在我的数据库中创建了四个表

(皮革,衬里,领子,按钮)。

在我的网络表格中,我创建了四个列表框,每个人都有一个表格

listbox8 - >皮革

listbox9 - > ;衬里

listbox10->领

listbox11->按钮



每张桌子我有两张字段名称,价格

当用户选择一个项目时我想从数据表中检索此项目的价格。



我导入以下代码为listbox8



Hi guys ,
I'm trying to implement a simple webform (create your own product), so I create four tables
in my database (leather,lining,collar,button).
In my Webform I create four listboxs each one foe one table
listbox8 ->leather
listbox9 ->lining
listbox10->collar
listbox11->button

in every table i have two fields name,price
when the user select one item i want to retrieve the price for this item from the datatable.

I import the following code for listbox8

int priceleather = 0;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        String SelectedItem = ListBox8.SelectedItem.Text;
        SqlCommand command1 = new SqlCommand("Select price from createproduct where name=" + SelectedItem);
        con.Open();
        using (SqlDataReader read = command1.ExecuteReader())
        {
            while (read.Read())
            {
                string price = read["price"].ToString();
                priceleather = Convert.ToInt32(price);
            }
            
            GridView1.DataSource = read;

            read.Close();
            con.Close();
        }

    } 



但是我收到一条错误消息:ExecuteReader:还没准备好或连接属性?



为了让它起作用,我应该改变什么?



这样做是否正确实现我描述或我的内容应该更改一个表中的所有内容并通过已调用类型选择它们吗?



提前获得Thnx的时间和帮助

Jason


but i receive an error message : ExecuteReader: is not ready or Connection Property?

What I should change in order to make it work?

Is this way correct to implement something that i describe or I should change everything in one table and select them by a column "called" type ?

Thnx in advance for your time and your help
Jason

推荐答案



用这个替换你的sql命令,

Hi,
replace your sql command with this,
SqlCommand command1 = new SqlCommand("Select price from createproduct where name=" + SelectedItem,con); // you are missing con here.



注意(建议): -

永远不要在这样的查询中传递参数,它会使你的网站容易被sql注入。

Insead使用就像这样,


Note(Advise):-
Never pass parameter in query like this, it will make your site vulnerable for sql injection.
Insead use it like this,

SqlCommand command1 = new SqlCommand("Select price from createproduct where name=@name",con);
command1.Parameters.AddWithValue("@name", SelectedItem);



希望它可以帮到你。

谢谢。


Hope it helps you.
Thanks.


你应该用你创建的连接初始化你的命令连接。

试试这个



You should initialize your command connection with your created connection.
try this

con.Open();
            SqlCommand command1 = new SqlCommand("Select price from createproduct where name=" + SelectedItem, con);


这篇关于从列表框和不同的数据源中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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