How to use combo box in c# - c#

I have no idea where to start. i tried DataTable but it didn't work.(This is an easy question :) )
I tried everything
{
var test = new DataTable();
test.Columns.Add("test");
test.TableName = "test";
test.Columns.Add("test");
comboBox1.DataSource = test.XXXX ;
}

Assuming you mean winforms, something like:
DataTable test = new DataTable();
test.TableName = "test";
test.Columns.Add("foo", typeof(string));
test.Columns.Add("bar", typeof(int));
test.Rows.Add("abc", 123);
test.Rows.Add("def", 456);
ComboBox cbo = new ComboBox();
cbo.DataSource = test;
cbo.DisplayMember = "foo";
cbo.ValueMember = "bar";
Form form = new Form();
form.Controls.Add(cbo);
Application.Run(form);
(in particular, SelectedValue should give you the 123 and 456 - useful for ids, etc)

ComboBox.Items property, unless you want data from a database or something.

DataTable dt=new DataTable();
dt.Columns.Add("Col1",typeof(int));
dt.Columns.Add("Col2",typeof(String));
dt.Rows.Add(1,"A");
dt.Rows.Add(2,"B");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Col2";
comboBox1.ValueMember = "Col1";

You'll need to set the 'DataItemField' and 'DataValueField' to the appropriate column names in your datatable.

Related

How to fill DataGridViewComboBoxColumn from a database table column without using datareader

Here is my code:
SqlDataAdapter GridDataAdapter = new SqlDataAdapter(query, con);
DataSet GridDataSet = new DataSet();
GridDataAdapter.Fill(GridDataSet, tbln);
dataGridView1.DataSource = GridDataSet;
DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn();
dataGridView1.DataMember = tbln;
Here, I want to fetch data for DataGridViewComboBox from a database table column.
How can I fill the DataGridViewComboBoxColumn without using a DataReader?
You already have the dataset filled, you could just iterate over the row collection if it contains the values that you want the DGVCombo to contain. So, the most straightforward way would be something along the lines of:
foreach(DataRow r in GridDataSet.Tables[0].Rows)
{
dgvCB.Items.Add(r["MyColumn"]);
}
Where .Tables[0] has the column("MyColumn") that you are looking for...
This should be what you need...
DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn();
dgvCB.Name = "lastname";
dgvCB.DataSource = tbln;
dgvCB.HeaderText = "Last";
//uncomment this to actually select the value in the combo box
//dgvCB.DataPropertyName = "lastname";
dgvCB.ValueMember = "lastname";
dataGridView1.Columns.Add(dgvCB);

loading combobox with datasource

i want to fill a combobox with data from the database when the page load
I had written the code as below
private void QuotationForm_Load(object sender, EventArgs e)
{
MessageBox.Show("hghjgvhg");
comboboxload();
}
public void comboboxload()
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobecode from jobcodemastertable",oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("jobpk", typeof(int));
dt.Columns.Add("jobcode", typeof(string));
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
oleDbConnection1.Close();
}
it doesnot deturns an error or exception but doesnot load the combobox with data values
try this
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
You may need to bind datatable's view with combo box
cmbjobcode.DataSource = dt.DefaultView;
You're missing the DataBind method
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
//here
cmbjobcode.DataBind();
oleDbConnection1.Close();
You have to call DataBind method on your combo. Thats why its not populating.

ComboBox.ValueMember and DisplayMember

How do i set this values? I have a DataTable with all the data i want to set in the combobox, but i cant find how to set it.
I tried
ComboBox1.DataSource = dataTable;
ComboBox1.ValueMember = "id"; // --> once hes here, he just jumps out the method
ComboBox1.DisplayMember = "name";
No compilation error, warning, nothing.. just jumps out!
This is the query to fill the DataTable
"Select * from \"Table\""
I checked with the debugger and the datatable was filled. The columns names are "id" and "name". ComboBox is blank. I'm filling it for the first time!
You should not set datasource of your listbox and/or combobox in this order
ComboBox1.DataSource = dataTable;
ComboBox1.ValueMember = "id";
ComboBox1.DisplayMember = "name";
Instead, this is correct order:
ComboBox1.ValueMember = "id";
ComboBox1.DisplayMember = "name";
ComboBox1.DataSource = dataTable;
NOTE: setting datasource should be last line.
If you set datasource first, SelectedIndexChanged event will fire and you may get the cast error or other exception.
Using keyvalue pairs to populate a combobox
A neat way to populate combo boxes is to set the datasource to a list of keyvalue pairs. It may also inspire using data stored in a list of some kind:
//Some values to show in combobox
string[] ports= new string[3] {"COM1", "COM2", "COM3"};
//Set datasource to string array converted to list of keyvaluepairs
combobox.Datasource = ports.Select(p => new KeyValuePair<string, string>(p, p)).ToList();
//Configure the combo control
combobox.DisplayMember = "Key";
combobox.ValueMember = "Value";
combobox.SelectedValue = ports[0];
The datasource can be populated using this syntax as well:
ports.Select(p => new { Key = p, Value = p }).ToList();
The technicue may be expanded with more property names for multiple column lists.
Objects that are already key-value pairs like Dictionary items can be used directly
combobox.DataSource = new Dictionary<int, string>()
{
{0, "COM1"},
{1, "COM2"},
{2, "COM3"},
}.ToList();
combobox.ValueMember = "Key";
combobox.DisplayMember = "Value";
Tuples can be initialized and used like this
var ports= new List<Tuple<int, string>>()
{
Tuple.Create(0, "COM1"),
Tuple.Create(1, "COM2"),
Tuple.Create(2, "COM3")
};
combobox.DataSource = ports;
combobox.ValueMember = "Item1";
combobox.DisplayMember = "Item2";
ComboBox1.DataSource= dt; //the data table which contains data
ComboBox1.ValueMember = "id"; // column name which you want in SelectedValue
ComboBox1.DisplayMember = "name"; // column name that you need to display as text
They take strings...
ComboBox1.ValueMember = "id";
ComboBox1.DisplayMember = "name";
I had the same trouble. In my case, SelectedIndexChanged event fires and just jumps out the method. Try do not use SelectedIndexChanged event. Or something like this:
ComboBox1.SelectedIndexChanged -= new System.EventHandler(ComboBox1_SelectedIndexChanged);
ComboBox1.DataSource = dataTable;
ComboBox1.ValueMember = "id";
ComboBox1.DisplayMember = "name";
ComboBox1.SelectedIndexChanged += new System.EventHandler(ComboBox1_SelectedIndexChanged);
It worked for me. =)
ComboBox1.ValueMember = dataTable.Columns["id"].ColumnsName; // column name which the values are not visible
ComboBox1.DisplayMember = dataTable.Columns ["name"].ColumnsName;
/*
column name that you need to select item by proprity :
ComboBox1.SelectedItem;
Or you can use easly this :
ComboBox1.Text;
*/
ComboBox1.DataSource= dataTable; //the data table which contains data
// and this should be last :)
public class ComboDeger {
private string yazi;
private int deger;
public ComboDeger(string stryazi, int strdeger) {
this.yazi = stryazi;
this.deger = strdeger;
}
public string yazisi {
get {
return yazi;
}
}
public int degeri {
get {
return deger;
}
}
}
private void combobox_doldur() {
ArrayList ComboDegerleri = new ArrayList();
ComboDegerleri.Add(new ComboDeger("9 : NORMAL", 9));
ComboDegerleri.Add(new ComboDeger("10 : ENGELLÄ°", 10));
comboBox1.DataSource = ComboDegerleri;
comboBox1.DisplayMember = "yazisi";
comboBox1.ValueMember = "degeri";
}
private void Form3_Load(object sender, EventArgs e) {
con.Open();
combobox_doldur();
// Populate the COMBOBOX using an array as DataSource.
}
you could specify like this
ComboBox1.ValueMember = "id";
ComboBox1.DisplayMember = "name";

Bind ComboBox to DataSet in code behind (no XAML)

How to bind a Combo Box to DataSet in code behind, without using XAML at all:
I tried the following, but all my combobox items are "System.Data.DataRowView" instead of the actual value. What is wrong?
string str = #"SELECT * FROM FooTable";
da.SelectCommand = new SqlCeCommand(str, connection);
da.Fill(devDs, "FooTable");
dt = ds.Tables["FooTable"];
comboBox1.ItemsSource = devDt.DefaultView;
You will have to set DisplayMemberPath property
combobox.DisplayMemberPath = "ColumnName"
You can use comboBox1.DisplayMemberPath to set which column in your table should be used for UI presentation.
Test sample:
var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Rows.Add(1, "Test1");
dataTable.Rows.Add(2, "Test2");
comboBox1.ItemsSource = dataTable.DefaultView;
comboBox1.DisplayMemberPath = "Name";

C#: Bind XML to ComboBox via DataSet

I am trying to get this code work for about 2 hours =( I am new to C# and don't know all the .NET library classes.
The target is to populate XML data to comboBox
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("table1");
dataTable.Columns.Add("col1", typeof(string));
dataSet.Tables.Add(dataTable);
StringReader strR = new StringReader("<root><parm1>val1</parm1><parm2>val2</parm2></root>");
dataSet.ReadXml(strR);
comboBox1.DataSource = dataSet.Tables[0];
comboBox1.DisplayMember = "col1";
comboBox1.ValueMember = "col1";
Well, it doesn't work as expected. The ComboBox should show
val1
val2
I don't really understand how column names of DataTable in a DataSet are related to XML-Tags... Maybe that's the point?
Thank You in advance!
The following should work:
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("table1");
dataTable.Columns.Add("col1", typeof(string));
dataSet.Tables.Add(dataTable);
StringReader strR = new StringReader("<root><table1><col1>val1</col1></table1><table1><col1>val2</col1></table1></root>");
dataSet.ReadXml(strR);
comboBox1.DataSource = dataSet.Tables[0];
comboBox1.DisplayMember = "col1";
comboBox1.ValueMember = "col1";
The names of the tables and the columns need to be consistent between your C# objects and XML data.

Categories

Resources