Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
Little Programmer Avatar asked Jul 11 '16 12:07

Little Programmer


3 Answers

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();
like image 124
MANISH KUMAR CHOUDHARY Avatar answered Nov 18 '22 16:11

MANISH KUMAR CHOUDHARY


private List<string> ComboBoxList = new List<string>();

Create this outside of the method you are currently in. This List will allow you to use it in any method within the class.

private List<string> ComboBoxList;

or Try this instead of the top piece of code. They both work.

SqlDataReader sqlReader = sqlCmd.ExecuteReader();
                while (sqlReader.Read())
            {

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

Create a new list and add each name to the list.

like image 2
Brendon Avatar answered Nov 18 '22 15:11

Brendon


I'm sure there's a more elegant method, but this works

List<string> values = this.ComKeyType.Items
                      .Cast<object>()
                      .Select(x => x.ToString().Split('=')[1].Replace(" }", "").Trim())
                      .ToList();
like image 1
Ángel Ibáñez Avatar answered Nov 18 '22 16:11

Ángel Ibáñez