Monday 31 December 2012

Step By Step Fill Dropdown List using Database in ASP.NET using C#

Step By Step Fill Dropdown List using Database in ASP.NET using C#

In this example we use a Dropdown List and a Grid View. The Dropdown List fills from column value of the table. If we select an item from Dropdown List the record of selected field will be shown in Grid View.

Default.aspx

<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:DropDownList ID="DropDownList1" runat="server"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        </asp:DropDownList>
        <br />
   
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    </form>
</body>
</html>


Default.aspx.cs


using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;
    protected void Page_Load(object sender, EventArgs e)
    {
      
        con=new SqlConnection(@"Data Source=VSC3-121\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
        con.Open();
        if(!IsPostBack)
        {

            DropDownList1.Items.Insert(0, new ListItem("--Select Text--","--Select Text--"));
            filldropdownlist();
        }

    }


  
    public void filldropdownlist()
    {

        cmd = new SqlCommand("select * from stud",con);
        dr = cmd.ExecuteReader();
        while(dr.Read())
        {
            DropDownList1.Items.Add(dr[0].ToString());

        }
        dr.Close();
    
 
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        cmd = new SqlCommand("select * from stud where id='" + DropDownList1.SelectedItem.ToString() + "'", con);
        dr = cmd.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();

    }
}

Database















Share This
Previous Post
Next Post

0 Comments: