我正在尝试生成一个GridView并由DropDownList SelectedValue填充它
我有一个DropDownList绑定到Country数据表和GridView绑定到State数据表,通过更改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();
}最后,我要把这些函数称为:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
FillDropdownList();
}
}
protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
{
BindGrid();
}.aspx文件:
<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的值时,GridView没有改变
发布于 2016-05-24 12:22:19
用于Dropdownlist列表集AutoPostBack = true
https://stackoverflow.com/questions/37413081
复制相似问题