C# - Fill a combo box with a DataTable
You need to set the binding context of the ToolStripComboBox.ComboBox.
Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.
I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?
If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.
var languages = new string[2];
languages[0] = "English";
languages[1] = "German";
DataSet myDataSet = new DataSet();
// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add(lName);
for (int i = 0; i < languages.Length; i++)
{
DataRow lLang = lTable.NewRow();
lLang["Language"] = languages[i];
lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);
toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
toolStripComboBox1.ComboBox.DisplayMember = "Language";
toolStripComboBox1.ComboBox.BindingContext = this.BindingContext;
How to fill combobox with Datatable column C#
I think you need to use Display and Value members properties to work with display data.
cbReviewers.DataSource = Reviewers_table
cbReviewers.DisplayMember = "ColumnNameThatContainsText"
cbReviewers.ValueMember = "ColumnNameThatContainsValue"
Fill ComboBox with DataTable result
Change your query like this
SELECT (Cast(id As varchar) + ' - ' + name + ' ' + last_name) As DisplayItem, Id FROM ...
then fill the table using that query.
To fill the blank item at the first row. use following code.
Dim row As DataRow = dtTable.NewRow()
row("DisplayItem") = "Enter Value or leave it blank"
row("ID") = -1
dtTable.Rows.InsertAt(row, 0)
Then bind the combobox with that datatable.
Combobox1.DisplayMember = "DisplayItem"
Combobox1.ValueMember = "Id"
Combobox1.DataSource = dtTable
Fill data into combobox from datatable
You can check if the combobox is already loaded or not.
private void txtleavetype_MouseClick(object sender, MouseEventArgs e)
{
try
{
if(txtleavetype.Items.Count==0){
con = new SqlConnection(cs.DBConn);
con.Open();
cmd = new SqlCommand(" select leavestype from hrsettings", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtleavetype.Items.Add(dr["leavestype"]);
}
dr.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Or else you can clear the list items before adding.
private void txtleavetype_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtleavetype.Items.Clear();
con = new SqlConnection(cs.DBConn);
con.Open();
cmd = new SqlCommand(" select leavestype from hrsettings", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtleavetype.Items.Add(dr["leavestype"]);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
As per the comment, You can also move the below code to Page_Load event and use if when it is not a post back.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
txtleavetype.Items.Clear();
con = new SqlConnection(cs.DBConn);
con.Open();
cmd = new SqlCommand(" select leavestype from hrsettings", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtleavetype.Items.Add(dr["leavestype"]);
}
dr.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Hope This Helps!
C# Fill combo box from SQL DataTable
I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable
, you can do it this way:
using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
For more information take a look at SqlDataReader reference on MSDN.
In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.
How to get values from DataTable to combobox?
You need to bind a handler to cmbCategory.SelectedIndexChanged like so:
cmbCategory.SelectedIndexChanged += cmbCategory_SelectedIndexChanged;
then define a method
void cmbCategory_SelectedIndexChanged(object sender, EventArgs e)
{
// get the selection
DataRowView drv = (DataRowView)cmbCategory.SelectedItem;
// and display the info
txtUser.Text = drv["username"].ToString();
txtPassword.Text = drv["password"].ToString();
}
display two columns from a datatable in combobox
RESOLVED !!
public void combobox1_load()
{
da = new SqlDataAdapter("select concat(NOM_PERSONNE,' ',PRENOM_PERSONNE) as 'nom_prenom' from PERSONNE ", cn);
dt = new DataTable();
try
{
cn.Open();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "nom_prenom";
// comboBox1.ValueMember = "ID_PERSONNE";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
Populate TextBox with Text from DataTable - Combo Box
Looks like you might be declaring your datatables as local variables for that method.
Place the DataTable
declaration in the space between Namespace
declaration and the class constructor
Namespace MyProject
{
public sealed partial class MyClass : Page
{
//Class wide variables go here
DataTable mytable = new DataTable();
class MyClass()
{
}
}
}
After that you should be able to reference your DataTable
within the ComboBox.SelectionChanged
event to assign your value to the TextBox
Edit:
Within the ComboBox.SelectionChanged
event use
TextBox.Text = ComboBox.SelectedValue.ToString();
where TextBox
is the name of the TextBox to assign to, and ComboBox
is the name of the ComboBox you want to get the value from.
or, if like in your case, its a third value the combobox can't handle directly
TextBox.Text = DataTable.Rows[ComboBox.SelectedIndex]["Note"].ToString()
Related Topics
Getting Specified Node Values from Xml Document
Capture Multiple Key Downs in C#
Model-View-Presenter in Winforms
Creating a Very Simple Linked List
How to Do Network Discovery Using Udp Broadcast
How to Programmatic Disable C# Console Application's Quick Edit Mode
Should I Use Two "Where" Clauses or "&&" in My Linq Query
Mono Https Webrequest Fails with "The Authentication or Decryption Has Failed"
Incremental JSON Parsing in C#
Force Browser to Download PDF Document Instead of Opening It
Use Reflection to Invoke an Overridden Base Method
How to Pass Parameters to the Custom Action
What Is the Fastest Way to Create a Checksum for Large Files in C#
How to Get the Index of an Item in a List in a Single Step
Check If Instance Is of a Type
How to Show File Copy Progress Using Fileinfo.Copyto() in .Net