Search code examples
c#comboboxdynamic-variables

C# combobox adding multiple items text and values from database dynamically


I am trying to list multiple companies in a combobox. These companies populate from database table tbl_companies. Combobox value should be id of table(Which is primary key of the table). Text should be the name of company. Like id=1 and name = "XYZ". Code is

      string connStr = "My Connection string";
        SqlConnection conn = new SqlConnection(connStr);

        string strQuery = "SELECT * FROM tbl_Companies ORDER BY id ASC";
        SqlCommand cmd = new SqlCommand(strQuery, conn);

        conn.Open();

        SqlDataReader companyRead = cmd.ExecuteReader();

        if (companyRead.HasRows)
        {
            while (companyRead.Read())
            {
                int cId = (Convert.ToInt16(companyRead["id"].ToString()));
                cmbCompany.Items.Insert(cId, companyRead["name"].ToString());
            }
        }
        conn.Close();

When I am executing the code, getting the following error. System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index'

For reference, I am also sharing the [enter image description here]screenshot of code with error1

I need guidance, how to fix the problem.


Solution

  • Your error is in the Item.Insert method where the first parameter should be the position in the already existing items collection where you want to insert the new value and not the Item's value.

    Instead of using this manual loop you could simply set the combo datasource to a DataTable and set the DisplayMember and ValueMember properties

    string connStr = "My Connection string";
    using(SqlConnection conn = new SqlConnection(connStr))
    {
        string strQuery = "SELECT * FROM tbl_Companies ORDER BY id ASC";
        SqlCommand cmd = new SqlCommand(strQuery, conn);
        conn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader())
        cmbCompany.DisplayMember = "name";
        cmbCompany.ValueMember = "id";
        cmbCompany.DataSource = dt;
    }
    

    Consider also that once you set the Datasource property in this way you shouldn't manually insert new items, instead you add elements to the underlying DataTable and refresh the combo datasource binding