Populating ComboBox from SQL in C# - 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";

Related

Setting value to ComboBoxs item #C

I'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
You need to set the data source of the combobox.
Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";

not able to set default value in combobox : C#

I was trying to add a default value ("--select item--") in existing ComboBox which is getting filled by Database table. Here is my code.
SqlConnection conn = new SqlConnection("Server = .\\SQLEXPRESS; Initial Catalog= Student; Trusted_Connection = True");
string query = "select Id, Name from abc1";
SqlDataAdapter da = new SqlDataAdapter();
conn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
comboBox1.DataSource = dt;
comboBox1.ValueMember = "Id";
comboBox1.DisplayMember = "Name";
Everything is working fine in above code and I'm getting CB filled with desired values.
Now when I try to insert default value using below, then it is throwing an error. This way was tried here
comboBox1.Items.Insert(0, "Select"); //this is throwing an error
comboBox1.SelectedIndex = 0;
I further explored below code to add default item.
comboBox1.SelectedIndex = -1;
comboBox1.Text = "Select an item";
This added an item as desired, but on any event, CB loses this value. After SelectIndexChanged event, I lose this value. So this cannot be my solution.
Any advise?
I'd rather not intefere into binding, but edit SQL instead:
string query =
#"select 0 as Id, -- or whatever default value you want
'select' as Name,
0,
union all
-- your original query here
select Id,
Name,
1
from abc1
-- to have default value on the top
order by 3 asc";
Insert's second parameter is expecting a ComboBox.ObjectCollection object.
Try doing this:
Having a class
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
}
And using:
// This could be inline, but for simplicity step by step...
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
//or
comboBox1.Items.Insert(0, item);
You can add programmatically the item to the datatable
DataRow dr = dt.NewRow();
dr["id"] = "0";
dr["name"] = "Select";
dt.Rows.InsertAt(dr, 0);
then you can set the datasource
comboBox1.DataSource = dt;
If you just want to show a suggestion text to your user, the "EDIT" part of this answer may help (can only work if your ComboBox's DropDownStyle is not set to DropDownList).
But if you really want some "Select" item in your ComboBox, try this:
void Form1_Load(object sender, EventArgs e)
{
//load your datatable here
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
comboBox1.Items.Add(new { ID = 0, Name = "Select" });
foreach (DataRow a in dt.Rows)
comboBox1.Items.Add(new { ID = a["ID"], Name = a["Name"] });
comboBox1.SelectedIndex = 0;
comboBox1.DropDown += new EventHandler(comboBox1_DropDown);
comboBox1.DropDownClosed += new EventHandler(comboBox1_DropDownClosed);
}
void comboBox1_DropDownClosed(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
{
comboBox1.Items.Insert(0, new { ID = 0, Name = "Select" });
comboBox1.SelectedIndex = 0;
}
}
void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(new { ID = 0, Name = "Select" }))
comboBox1.Items.Remove(new { ID = 0, Name = "Select" });
}

How to clear datatable values when using two datatables?

I have two DataTables after passing query the second DataTable Shows the FirstDataTable values. Please find my code
My connection class is
public class Connection
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
public SqlDataAdapter ad;
public DataTable dt = new DataTable();
public DataTable gettable(string cmdtxt)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Open();
dt.Clear();
ad = new SqlDataAdapter(cmdtxt, conn);
ad.Fill(dt);
return dt;
}
}
My code is
String qry="";
DataTable shiftdt = new DataTable();
DataTable empdt = new DataTable();
qry = "select ShiftID from ShiftGroup where ShiftName="#Shift";
shiftdt = conn.gettable(qry);
qry = "select EmpCode from EmployeeShift where GroupCode="#gcode";
empdt = conn.gettable(qry);
First,shiftdt shows proper output ShiftID and when go ahead empdt shows first column as ShiftID and Second Column as EmpCode. Actually I dont want ShiftID in empdt. And again when I go ahead Shiftdt values changes to EmpCode. May I know the reason?
I tried `Dot net learner,when I change code as per him, I have a
dropdown class it shows error like
`Error 8 'Sample.Connection' does not contain a definition for 'dt' and no extension method 'dt' accepting a first argument of type 'Sample.Connection' could be found (are you missing a using directive or an assembly reference?
. That calss is
public class Dropdown
{
Connection con = new Connection();
public void dropdwnlist(string qry, DropDownList ddl)
{
con.gettable(qry);
if (con.dt.Rows.Count > 0)
{
if (con.dt.Columns.Count == 2)
{
string str1 = con.dt.Columns[0].ColumnName.ToString();
string str2 = con.dt.Columns[1].ColumnName.ToString();
ddl.DataValueField = str1;
ddl.DataTextField = str2;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str1);
con.dt.Columns.Remove(str2);
}
else
{
string str = con.dt.Columns[0].ColumnName.ToString();
ddl.DataValueField = str;
ddl.DataTextField = str;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str);
}
}
ddl.Items.Insert(0, ("--Select--"));
}
}
You Have dt as Global variable in Class So Please Make it Local variable for Function or Assign new DataTable on starting of gettable function.
Your revised Code should be
public class Connection
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
public SqlDataAdapter ad;
public DataTable gettable(string cmdtxt)
{
DataTable dt = new DataTable();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Open();
dt.Clear();
ad = new SqlDataAdapter(cmdtxt, conn);
ad.Fill(dt);
return dt;
}
}
I had revised code as per your need please check it.
You shouldn't use Connection Class DataTable(dt) Variable to bind dropdown instead Declare DataTable Variable Local for Dropdown Class and use it to bind Dropdown.
Revised Code for Dropdown Class
public class Dropdown
{
Connection con = new Connection();
public void dropdwnlist(string qry, DropDownList ddl)
{
DataTable dt =con.gettable(qry);
if (dt.Rows.Count > 0)
{
if (dt.Columns.Count == 2)
{
string str1 = dt.Columns[0].ColumnName.ToString();
string str2 = dt.Columns[1].ColumnName.ToString();
ddl.DataValueField = str1;
ddl.DataTextField = str2;
ddl.DataSource = dt;
ddl.DataBind();
dt.Columns.Remove(str1);
dt.Columns.Remove(str2);
}
else
{
string str = dt.Columns[0].ColumnName.ToString();
ddl.DataValueField = str;
ddl.DataTextField = str;
ddl.DataSource = dt;
ddl.DataBind();
dt.Columns.Remove(str);
}
}
ddl.Items.Insert(0, ("--Select--"));
}
}

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

Categories

Resources