In this Article, we will see How to bind data in ComboxBox from database in C# Windows Form Application. In previous post, we saw How to:
- Create a simple Windows Form Login Application in C#
- Insert, Update and Delete Record in DataGridView C#
- Search Record in DataGridView C#.
Let's Begin:
1. Go to New -> Project -> Select Windows Form Application.
2. Create a Database (named as Sample). Add a Table tbl_Country. The following is the table schema for creating tbl_Country.
3. Drop Label and ComboBox control from the toolbox.
Form1.cs Code:
In the above code, I have created fillComboBox() method for filling the ComboBox with data and also created cmb_Country_SelectedIndexChanged event which fires when the SelectedIndex property changed.
Form1.cs Code:
using System;
using System.Data;
using
System.Windows.Forms;
using
System.Data.SqlClient;
namespace ComboBoxDataBind
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Form Load
private void Form1_Load(object sender, EventArgs e)
{
fillComboBox();
}
//fillComboBox method for filling the ComboBox with Data
private void fillComboBox()
{
try
{
using (SqlConnection con =
new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated
Security=true;"))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("Select * from
tbl_Country", con);
DataTable
dt = new DataTable();
adapt.Fill(dt);
//Set Displaymember as Country
cmb_Country.DisplayMember = "Country";
//Set ValueMember as ID
cmb_Country.ValueMember = "ID";
cmb_Country.DataSource = dt;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//cmb_Country_SelectedIndexChanged Event
private void
cmb_Country_SelectedIndexChanged(object sender, EventArgs e)
{
lbl_DisplayValue.Text = cmb_Country.SelectedValue.ToString();
}
}
}
|
Final Preview:
Hope you like it. Thanks.
[Download Source code via Google Drive]
I am strugglling with "Data Source=.;Initial Catalog=Sample;Integrated Security=true;"))
ReplyDeleteas I do not know how to write it in my application.
Can you tell me what it is and also what I need to write for my application.
Regards
"Data Source=.;Initial Catalog=Sample;Integrated Security=true;" is a connection string that includes the source database name, and other parameters required to establish the initial connection with database. Please create a Database (named as Sample) and add a Table tbl_Country and follow each step as shown in this Post.
Delete88
ReplyDeleteGreat contribution!
ReplyDeletewow...so nice
ReplyDeletewow...so nice
ReplyDeletegood Man, thanks,can i have your direct email address plz?
ReplyDeleteIn windows 10 and windows 7 what is dns server not available
ReplyDeleteHow can we get combo box selected data and assign to class object. Plz plz answer anyone
ReplyDeleteThis doesn't work.
ReplyDeleteIt's working fine. Always try to share the error which you are getting so that we can help you on that issue.
Delete