2

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.

1
  • try Items.Add instead of insert. Commented Jul 27, 2021 at 19:27

2 Answers 2

1

You are inserting at a specific index, and when the list is empty at the start, an index of '1' is considered out of range.

Try:

cmbCompany.Items.Add(companyRead["name"].ToString());

instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you slacker for your response. But in my case, its not fulfilling my requirements.
0

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

3 Comments

I wanted to set the table id values as combobox index values. Right now I am getting the default index values like 0,1, 2, 3. In database table, companies ids are 1,3,4 & 6. Actually I have to save the company ID while updating the record.
I think that this is a wrong idea. You shouldn't link the combobox index (a ui feature) to the company id ( a database property) they are destined to diverge at some point. and you can't index something that doesn't exist. The approach given in my example keeps the two things separated. You get the current ID from the SelectedValue property. Remember to check for null before using SelectedValue/SelectedItem
Thanks again @steve. Already fixed the issue as you mentioned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.