Select dropdownlist value and display gridview from different tables ASP.NET

asp.netdrop-down-menu

I create web application. I add drop down list. I connect list with Names of Tables Categories. for example 1, 2, 3. When I select value 1 it should be created grid view populated with data from Table 1. When I select 2 create grid view populated with data from Table 2..
I connect tables in the SQL database. PrimaryKey Category ID, foreign key1, foreign key2 approprietly.

I know how to populate grid view by select value in the drop down list, but the values from one table. In this case I have 4 tables and I don't know how to realise that. Is there somebody who can help me? by some tutorial, or piece of code? thanks

Best Answer

try this...

aspx page:

<body>
    <form runat="server">
    <asp:DropDownList runat="server" ID="ddlDb" AutoPostBack="True" OnSelectedIndexChanged="ddlDb_SelectedIndexChanged">
        <asp:ListItem Text="-- Select --" Value=""></asp:ListItem>
        <asp:ListItem Text="Students" Value="Students"></asp:ListItem>
        <asp:ListItem Text="Classes" Value="Classes"></asp:ListItem>
    </asp:DropDownList>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    </form>
</body>

aspx.cs:

protected void ddlDb_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(ddlDb.SelectedValue))
    {
        var dbPath = Server.MapPath(@"\App_Data\Database1.mdf");
        var scon = "Data Source=.\\SQLEXPRESS;AttachDbFilename='" + dbPath + "';Integrated Security=True;User Instance=True";
        var cmd = "select * from " + ddlDb.SelectedValue;

        var dt = new DataTable();
        var da = new SqlDataAdapter(cmd, scon);
        da.Fill(dt);

        GridView1.DataSource = dt;
        GridView1.DataBind();                
    }
}

enter image description here

enter image description here

Related Topic