How to fill Combobox Items from Database in Windows Forms Application in C#.
Database
For filling the ComboBox, First have to create a table in Microsoft SQL Server Database as shown below.
When creating a table make Identity Specification as true for column 'ID'.
Set the table name as shown below.
Firstly you need to add a ComboBox control to the Windows Form from the Visual Studio ToolBox as shown below.
Form Design
You will need to import the following namespace.
using System.Data.SqlClient;
Below is the sample code for Adding Items to ComboBox from Database.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillCombobox();
}
protected void FillCombobox()
{
string conString = @"server=YOUR SERVERNAME; database=YOUR DATABASE NAME; uid=***; password=*****;";
SqlConnection conn = new SqlConnection(conString);
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select ID,EmployeeName from Employee group by ID, EmployeeName", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
comboBox1.DisplayMember = "EmployeeName";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillCombobox();
}
protected void FillCombobox()
{
string conString = @"server=YOUR SERVERNAME; database=YOUR DATABASE NAME; uid=***; password=*****;";
SqlConnection conn = new SqlConnection(conString);
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select ID,EmployeeName from Employee group by ID, EmployeeName", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
comboBox1.DisplayMember = "EmployeeName";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
//Exception Message
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
I hope this page will helps to fill ComboBox Items in Windows Forms Application in C#. Thanks.
No comments:
Post a Comment