How to bind data to dropdownlist in asp.net?

Try the following code in aspx page:


<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False"></asp:gridview>

Try the below code in aspx.cs page in page_load:

Add below namespace:

using System.Data.SqlClient;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection cn = new 

SqlConnection(ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from student", cn);

cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "username";
DropDownList2.DataValueField = "userid";
cmd.Dispose();
}
}
}    

Try the below code in aspx.cs page in DropDownList click event:


protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Your 

ConnectionString name"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("select * from student where ID=@userid ", cn);

cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@userid", DropDownList2.SelectedValue);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cmd.Dispose();
}
}

About the Author

avatar