Bayan
Bayan

Reputation: 82

asp.net generate Gridview by DropDownList IndexChange

I'm trying to generate a GridView and fill it by DropDownList SelectedValue

I have a DropDownList bind to Country data table and GridView bind to State data table and by changing the value of the DropDownList the data in the GridView change too

i'v tried this code: this to fill the dropdownlist:

protected void FillDropdownList()
{
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter adp = new SqlDataAdapter();
    DataTable dt = new DataTable();
    try
    {
        cmd = new SqlCommand("Select * from Country", con);
        adp.SelectCommand = cmd;
        adp.Fill(dt);
        DropDownListCountry.DataSource = dt;
        DropDownListCountry.DataTextField = "CountryName";
        DropDownListCountry.DataValueField = "CountryID";
        DropDownListCountry.DataBind();
        //DropDownListCountry.Items.Insert(0, "-- Select --");
        //OR    ddlEmpRecord.Items.Insert(0, new ListItem("Select Emp Id", "-1"));
    }
    catch (Exception ex)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
    }
    finally
    {
        cmd.Dispose();
        adp.Dispose();
        dt.Clear();
        dt.Dispose();
    }
}

and this to generate the gridView

 protected void BindGrid()
{

    con.Open();
    SqlCommand com = new SqlCommand("select *  from State where CountryID='" + DropDownListCountry.SelectedValue + "'", con);
    SqlDataAdapter sda = new SqlDataAdapter(com);

    DataTable dt = new DataTable();
    sda.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    con.Close();
}

and finally that's where i'm calling the functions:

 protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    { 
        FillDropdownList();

    }
}



 protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
{
    BindGrid();   
}

the .aspx file:

<asp:DropDownList ID="DropDownListCountry" runat="server"  DataTextField="CountryName" DataValueField="CountryID" OnSelectedIndexChanged="DropDownListCountry_SelectedIndexChanged" >
        </asp:DropDownList>
        <br />

                    <!-- SqldataSource and GridView and Formview for State -->

        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
             <Columns>
        <asp:BoundField HeaderText="State Id" DataField="StateID" />
        <asp:BoundField HeaderText="State Name" DataField="StateName" />
        <asp:BoundField HeaderText="Country Id" DataField="CountryID" />
        
        </Columns>
        </asp:GridView>

but the code is not working and when i'm changing the value of DropDownList the GridView is not changing

Upvotes: 2

Views: 46

Answers (1)

Anup Sharma
Anup Sharma

Reputation: 2083

For your Dropdownlist set AutoPostBack = true

Upvotes: 1

Related Questions