How to display data in DataGridView by combobox selected values

03/06/2017   02:51:10 PM

Hello,in this c# tutorial i will explain how to display data from sql server database to DataGridView control in c# by combobox selection.For that first we will display students name list to ComboBox.then from ComboBox selected student, details like name,dob,mailid display in to DataGridView

1 .Create a database name as StudentDetails using SQL SERVER. Create a Table name as StudentRegistration in this database.

Column Name    

DataTypes

Id

         Int [Identity Property Set =True]

StudentName

         varchar(50)

DOB          varchar(50)
MailId          varchar(50)

 

2. Open VisualStudio.Net / Select c# / Windows Application

3.Add DataGridView and Combobox controls From VS.Net / View / Toolbox on Form1.design.cs

4.Add the following code in to App.config file in </configuration> tag

<connectionStrings>
<add name="cn" connectionString="Data Source=.\sqlexpress;Initial Catalog=Studentdb;Integrated Security=True"/>
</connectionStrings>

 

5.Add a refrence System.Configurtation

Right click on refrences folder in project folder/Add Refernces / From Refrence Manager window/ Assemblies option / click on Framework option / select System.Configuration from list /click on ok

Now System.Configuration added in project

6.Create a class dbconnect.cs and add the following code in that class

 
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
 
namespace ComboboxToTextboxdb
{
class dbConnect
{
public static string dbconnectivity()
{
return ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
}
}
}

 

6.Add the following code on From1 Form1_Load event to display data from database to combobox and Combobox cmbStudentName_SelectedIndexChanged event to display Combobox selected value related data to DataGridView
 
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
namespace ComboboxToGridview
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection cn = new SqlConnection(dbConnect.dbconnectivity());
SqlDataAdapter da;
DataTable dt;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * From StudentRegistration", cn);
dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["StudentName"] = "Select Student Name";
dt.Rows.InsertAt(dr, 0);
cmbStudentName.ValueMember = "Id";
cmbStudentName.DisplayMember = "StudentName";
cmbStudentName.DataSource = dt;
}
private void cmbStudentName_SelectedIndexChanged(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * From StudentRegistration where StudentName='"+cmbStudentName.Text+"' ", cn);
ds = new DataSet();
da.Fill(ds, "StudentRegistration");
dgvData.DataSource = ds;
dgvData.DataMember = "StudentRegistration";
}
}
}

Output

                   

Support us by Sharing