如何在列表框中显示数据

如何在列表框中显示数据

本文介绍了如何在列表框中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在1个表单上有2个列表框,我希望每个列表框显示数据但是来自相同的sql表/数据库,我的代码>

hi i have 2 listboxes on 1 form , i want each listbox to display data but from the same sql table/database, my code >

private void addproduct_Load(object sender, EventArgs e)
        {
            DataSet st = new DataSet();
            string strConnectionString = "Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=tblproducts;Integrated Security=True";

            SqlConnection objconnection = new SqlConnection(strConnectionString);
            using (SqlCommand cmd = new SqlCommand("SELECT  [name,quantity,code,price] FROM [addproducts]",
            objconnection))
            {
                using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                {
                    adapter.Fill(st);
                }
            }

            var empList = st.Tables[0].AsEnumerable().Select(dataRow =>

            dataRow.Field<string>("name")).ToList();
            listBox1.DataSource = empList;

            listBox1.SelectedIndex = 0;




        }



所以我想在列表框2中显示数量,所以我试过复制整个代码,只是在这里和那里更改位,但我在var emplist上出错,尝试添加>



dataRow.Field< string>( name))。ToList();

listBox1.DataSource = empList;



listBox1.SelectedIndex = 0;



只是更改值但没有运气,请指出哪里或哪些我做错了,提前谢谢


so i want to show the quantity in listbox 2 , so ive tried copying the whole code and just change bits here and there, but i get an error on var emplist, tried just adding >

dataRow.Field<string>("name")).ToList();
listBox1.DataSource = empList;

listBox1.SelectedIndex = 0;

and just change the values but no luck, please point out where or what im doing wrong, thanks in advance

推荐答案

var empList = set.Tables[0].AsEnumerable().Select(dataRow => dataRow.Field<string>("name")).ToList();
ListBox1.DataSource = empList;
ListBox1.SelectedIndex = 0;
ListBox1.DataBind();

empList = set.Tables[0].AsEnumerable().Select(dataRow => dataRow.Field<string>("quantity")).ToList();
ListBox2.DataSource = empList;
ListBox2.SelectedIndex = 0;
ListBox2.DataBind();
</string></string>





您只需使用DataBind()方法。



You just have to use DataBind() method.


这篇关于如何在列表框中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:08