0

How could I make the options of my combobox a variable.

I want its values to depend on a certain field in my database.

for ex. If I have a table test and it has a field number.

Everytime I insert a value on my field it will be included in the options in my combobox.

so if i insert 1 into may table test. my combobox will have an option 1.

I wonder how to do it :|

rj tubera
  • 747
  • 4
  • 29
  • 51

3 Answers3

1

Using query and DataSource. Just get your data from the DB and bind it to the Combobox. You can do it via DataSource property.

List<string> myComboboxVaues = new List<string>()
{
    "Value 1",
    "Value 2",
    "Value 3"
};

this.comboBox1.DataSource = myComboboxVaues;

Instead of list of strings use retrieved from DB data.

Samich
  • 29,157
  • 6
  • 68
  • 77
  • how can i specify which table will he get the values? and on which column? – rj tubera Sep 11 '11 at 07:09
  • See http://stackoverflow.com/questions/600869/how-to-bind-a-list-to-a-combobox-winforms – Amittai Shapira Sep 11 '11 at 07:23
  • Specify in your sql query or if you are using Linq2Sql, Entity Framework, NHibernate or any other ORM - just bind your collection of `Test` entites and don't forget to specify `DisplayMember` and `ValueMember` in this case – Samich Sep 11 '11 at 07:27
  • Check following posts to get the details of implementation: [Populating WinForm Controls with ADO.NET](http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=111), [Populate data from database in a ComboBox](http://www.codeproject.com/KB/database/comboboxhtmlpage.aspx). – Samich Sep 11 '11 at 07:31
0

I like using foreach. Load the database record string into the array or directly into the foreach below.

string[] arr = new string[4]; // Initialize
arr[0] = "one";               // Element 1
arr[1] = "two";               // Element 2
arr[2] = "three";             // Element 3
arr[3] = "four";              // Element 4


foreach (string x in arr)
{
    comboBox1.Items.Add(x);
}
apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69
0

I think DataBinding is the best option.
Use the following properties for the ComboBox:
1. DataSource -> Table
2. DisplayMember and
3. ValueMember

Krishna
  • 688
  • 1
  • 7
  • 10