How to Bind Gridview when DropDownlist value is selected || Binding of Gridview and DropDownList in Asp.net.
The following example can be used in two ways. one is for binding the grid-view to retrieve the data from database. Another one is for binding the gridview when Dropdown list value is selected. you can select the particular records in the gridview according to DropDownlist values.
To implement this concept you need to follow the below steps
Step1 :
First you need to design a table in Sql Database to save the records in
database.
Step2:
Create a new Asp.net website in Visual Studio and write the following source code in the Default.aspx.cs page.
using System;
using
System.Configuration;
using
System.Data;
using
System.Linq;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Xml.Linq;
using
System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection
con = new SqlConnection("Data Source=SYSTEM2\\SQLEXPRESS;Initial
Catalog=sri1;Integrated Security=True");
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void Button1_Click1(object
sender, EventArgs e)
{
con.Open();
SqlCommand
cmd = new SqlCommand("select * from people", con);
SqlDataReader
dr = cmd.ExecuteReader();
while
(dr.Read())
{
TextBox1.Text = dr[0].ToString();
TextBox2.Text = dr[1].ToString();
TextBox3.Text = dr[2].ToString();
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void Button2_Click(object
sender, EventArgs e)
{
SqlDataAdapter
da = new SqlDataAdapter("select name from people", con);
DataTable
dt = new DataTable();
da.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "name";
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs
e)
{
SqlDataAdapter
da = new SqlDataAdapter("select * from people where name='" +
DropDownList1.SelectedItem.Text + "'",
con);
DataTable
dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
As of beginners like me, really your all blogs are much helpful, used easiest way to understand the code culture. Thanks Sridhar for your the pure work .. Keep it up more!!
ReplyDelete