ComboBox.ValueMember and DisplayMember - c#

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";

Related

C# WindowsForm Combobox showing wrong "Display Value"

Goal:
Get all file directories from MySQL and place them into a dictionary.
Display them into a combobox just as the filename. e.g. filename
Assign the combobox value as the the full directory. e.g. c:\users\user\desktop\filename.jpg
Code:
string filenames = "select filename from request_label_signoff where progress_user1 is null or progress_user2 is null";
//On load - load specific images from query above
private void Form15_Load(object sender, EventArgs e)
{
//Dict to store file into
Dictionary<string, string> files = new Dictionary<string, string>();
using (var conn = new MySqlConnection(connString))
{
conn.Open();
using (var cmd = new MySqlCommand(filenames, conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//add filename without extension and full directory
files.Add(Path.GetFileNameWithoutExtension(reader.GetString(0)), reader.GetString(0));
}
}
}
}
comboBox1.DataSource = new BindingSource(files, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
pictureBox1.Image = Image.FromFile(value);
}
Problem:
For some reason the display value for the combobox shows like this:
Text output: [abc 123, C:\Users...]
Whereas it should be abc 123 without the directory next to it.
Question:
Why does he combo-box display value show both items?
You need to change the order of assignment in the combobox.
The reasons are:
sometimes the displaymember assignment wont work. From
StackOverflow Answer
comment.
Sometimes, selectedIndex event might fire if you set datasource first. Reference Stackoverflow
Answer
Instead of:
comboBox1.DataSource = new BindingSource(files, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
it should be:
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = new BindingSource(files, null);
Instead of using this: Dictionary<string, string> files = new Dictionary<string, string>();
I have used: var choices = new Dictionary<string, string>();
As guided in the comment by hans-passant
And everything works. Not sure what the difference was.

Populating ComboBox from SQL in C#

I am trying to populate my combobox from sql but when i assign a value member to it, it gives me the following error
cannot explicitly convert int into string
Could you help me understand and correct my mistake?
void Fillcombo()
{
string query_select = "SELECT * FROM department";
DataTable dt = DataAccess.selectData(query_select);
SqlDataReader dr = DataAccess.selectDataReader(query_select);
while (dr.Read())
{
string dpt_name = dr.GetString(1);
int dpt_id = (int)dr.GetValue(0);
comboBox1.DataSource = dt;
comboBox1.ValueMember = dpt_id; // error here
comboBox1.DisplayMember = dpt_name;
}
}
You must assign name of column in DataSource (DataTable) to ValueMenmber and DisplayMember as string, and you don't need to use while loop, like this :
void Fillcombo()
{
string query_select = "SELECT * FROM department";
DataTable dt = DataAccess.selectData(query_select);
comboBox1.DataSource = dt;
comboBox1.ValueMember = "ColumnName_DepartmentID";
comboBox1.DisplayMember = "ColumnName_DepartmentName";
}
You should write it in a string format:
comboBox1.ValueMember = "dpt_id";

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.

c# converting from System.Data.DataRowView to string

i have a combobox whose datasource is a datatable. i need to loop through the items in the combobox, but how would i do this? i need to be able to convert each object of type 'System.Data.DataRowView' to string. any advice greatly appreciated!#
Based on your recent questions, it sounds like you are trying to figure out how to find or set the selected item in the combobox based on the text displayed in the item. I am not exactly sure how you have things set up, but please look at the following code and see if it helps:
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
dt.Rows.Add(3, "C");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
// use SelectedValue to select the item with ID == 2
comboBox1.SelectedValue = 2;
// use FindStringExact() to find the index of text displayed in the item
comboBox1.SelectedIndex = comboBox1.FindStringExact("C");
}
and using a combobox as set up above, you can get the text of the display member like this:
private void button2_Click(object sender, EventArgs e)
{
foreach (var item in comboBox1.Items)
MessageBox.Show(((DataRowView)item)["Name"].ToString());
}
Workaround for the same, hope it helps:
Convert the dataview source back to datatable and then loop through it.
DataView dt = (DataView)comboBox1.DataSource;
DataTable s = dt.Table;
foreach(DataRow dr in s.Rows)
MessageBox.Show(dr[0].ToString());
Well... to loop through a combobox, use (slightly pseudocoding, please don't c+p without working on the code):
var newItems = new List<string>();
for(var i = 0; i < combobox1.Items.Count; i++)
{
newItems.Add(combobox1.items[i].Text);
}
Then to access each item, use:
foreach(item in newItems)
{
var newVariable1 = item;
}
More info and your current code would be cool, I'd be able to help you more specifically with your problem that way.
Solution:
DataTable DtShow=new DataTable();
for (int i = 0; i < DtShow.Rows.Count; i++)
{
Console.WriteLine(DtShow.Rows[i].Field<string>(0));
}
** Field<string>(0) Column number start from 0
Hope this helps someone some day. Took me a while to come up with a solution for making a checkedboxlist populate from SQL server.
public partial class MemberSearch : Form
{
List<string> DataList = new List<string>(1);
public void GetTypesTable()
{
var CONEX = Properties.Settings.Default.Server_1_Conn;
var sql = "SELECT Type_List FROM List_Member_Types;";
DataTable dt = new DataTable();
using (SqlConnection c = new SqlConnection(CONEX))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
sda.Fill(dt);
DataView view = new DataView(dt);
DataTable s = dt;
foreach (DataRow ROW in s.Rows)
DataList.Add(ROW[0].ToString());
ckLstBox_MemTypes.DataSource = DataList;
}
}

How to use combo box in 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.

Categories

Resources