User283571144 posted
Hi Muhammad Sheraz Ahsan,
According to your description, I suggest you could use OnSelectedIndexChanged event to rebind the girdview when ddl changed.
More details, you could refer to below codes:
Aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" ="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>23</asp:ListItem>
<asp:ListItem>34</asp:ListItem>
<asp:ListItem>55</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
Codebehind
SqlConnection sqlcon = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet-CoreWithIdentity-1342045D-8996-4D0A-8EFB-053F49A08AFF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGrid();
}
}
void LoadGrid()
{
string query;
if (DropDownList1.SelectedIndex != 0)
{
query = "select * from Persons where Name = @test";
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.Parameters.Add("@test", SqlDbType.VarChar).Value = DropDownList1.SelectedValue.ToString();
}
else
{
query = "select * from Persons";
sqlcmd = new SqlCommand(query, sqlcon);
}
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
sqlcon.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LoadGrid();
}
Best Regards,
Brando