简体   繁体   中英

how to populate combo box from database and insert new item on index zero in C#

This code below works for me, but i have not been able to insert ---Select--- to the for first index with value zero, i have tried:

cboGrade.Items.Insert(0,"---Select---)

but it is not working for me. Also i want to able to retrieve and display the displaymember and displayvalue on the combo box while retrieving from database without items not being repeated:

private void LoadGrade()
    {
        using (SQLiteConnection conn = new SQLiteConnection(connstring))
        {

            try
            {
                string query = "select GradeCode, GradeName from Grade";
                SQLiteDataAdapter da = new SQLiteDataAdapter(query, conn);
                conn.Open();
                DataSet ds = new DataSet();
                da.Fill(ds, "OrgGrade");
                cboGrade.DisplayMember = "GradeName";
                cboGrade.ValueMember = "GradeCode";
                cboGrade.DataSource = ds.Tables["OrgGrade"];

            }
            catch (Exception ex)
            {

                MessageBox.Show("Error occured loading grade!");
            }
        }
    } 

Items only works if you have an unbound combo hence you either need to build the items array OR use binding.

What you need to do is insert into the DataTable you are binding like this:

DataTable dt = ds.Tables["OrgGrade"]
// generate the data you want to insert
DataRow newRow=  dt.NewRow();

newRow.GradeName = "-- Select --";
newRow.GradeCode = 0;
// insert in the desired place
dt.Rows.InsertAt(newRow, 0);

Then bind using:

cboGrade.DataSource = dt;

Similar to what you have.

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