asp.net通过DropDownList IndexChange生成Gridview

时间:2016-05-24 12:06:48

标签: c# html asp.net gridview drop-down-menu

我正在尝试生成GridView并按DropDownList SelectedValue填充

我有DropDownList绑定到国家数据表,GridView绑定到数据表并更改了{{{ 1}} DropDownList中的数据也会改变

我试过这段代码: 这将填写下拉列表:

GridView

这将生成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(); } }

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();
}

.aspx文件:

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

    }
}



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

但是代码无效,当我更改<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>的值时,DropDownList没有改变

1 个答案:

答案 0 :(得分:1)

对于您的下拉列表集AutoPostBack = true