简体   繁体   中英

display data to listbox C#

Listbox does not show data. Verified data is in database and I am not getting an error. Not sure where/what is wrong. Thanks in advance. My code is attached.

 private void UpDateList()
        {
            //  add data connection and fill data set.

            SqlConnection conn = new SqlConnection(dataSource);
            DataTable dt = new DataTable();
            string sqlString = "select * from Suppliers";
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            try
            {
                cmd.Connection = conn;
                conn.Open();
                cmd.CommandText = sqlString;
                da.Fill(ds);
                conn.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
            foreach(DataRow dRow in ds.Tables[0].Rows)
            {
                ArrayList values = new ArrayList();
                foreach(object value in dRow.ItemArray)
                {
                    values.Add(value);
                    _Suppliers.Add(values);
                }
            }    
            lstSuppliers.DataSource = _Suppliers;
            lstSuppliers.Update();
        }

It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)

Eg

LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";

And then for example, not required but an example possibility:

ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM