Little Programmer Little Programmer - 3 months ago 20
C# Question

How to put combobox Items in a list?

I added Items to a combobox using:

SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
string name = sqlReader.GetString(0);
combobox1.Items.Add(name);
}
sqlReader.Close();
conn.Close();


Now I want to put these value in a string list. Is that possible and how can I do that?

Answer

Simply you can do something like

string[] items = new string[combobox1.Items.Count];  

 for(int i = 0; i < combobox1.Items.Count; i++)
   {
       items[i] = combobox1.Items[i].ToString();
   }

Or if want to Create a string list directly from reader object than

var itemList=new List<string>();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
                while (sqlReader.Read())
                {

                    string name = sqlReader.GetString(0);
                    combobox1.Items.Add(name);
                    itemList.Add(name);
                }
                sqlReader.Close();
                conn.Close();
            }

Use of LINQ will make you job very easier

var arr = combobox1.Items.Cast<Object>()
      .Select(item => item.ToString()).ToArray();