Thursday, 5 April 2012

How to Bind Gridview and Dropdownlist in Asp.net || Bind GridView when Dropdown list Select Changed Event in Asp.net


The following code showing about Bind the Gridview and Dropdown list.
Binding the Gridview in two ways
1.Bind the Gridview normally when page load and
2.Bind the Gridview when Dropdownlist selected index changed event means by using dropdown list selected value then Bind the Gridview.

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=databaseName;Integrated Security=True");

    protected void Page_Load(object sender, EventArgs e)
    {
If(!page.IsPostBack)
{
BindGrid();
BindDdlList();
}

    }
private void BindGrid()
{

        con.Open();
        SqlCommand cmd = new SqlCommand("select * from students", 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();
        }
    }

private void BindDdlList()
{
    {
        SqlDataAdapter da = new SqlDataAdapter("select id,name from students ", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        DropDownList1.DataSource = dt;
       DropDownList1.DataValueField = "id";
        DropDownList1.DataTextField = "name";
        DropDownList1.DataBind();
    }

    protected void DropDownList1_SelectedIndexChanged(object sender,EventArgs e)
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from students where name='" + DropDownList1.SelectedItem.Text + "'", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

0 comments:

Post a Comment