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?
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();
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With