1
我想在GridView控件內部實現級聯DropDownList。我的代碼是下面給出:在ASP.NET中使用實體框架在Gridview中級聯DropdownList
的.aspx代碼
<asp:GridView ID="GridView1" runat="server" Width="550px"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1"
AutoPostBack="true" runat="server" DataTextField="State" DataValueField="StateID" onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2"
AutoPostBack="true" runat="server" DataTextField="City" DataValueField="CityId">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
代碼背後:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl1 = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl1 != null)
{
using (var context = new ABCEntities())
{
var _state= from u in context.State
select new
{
StateId= u.StateId,
State= u.State
};
ddl1.DataSource =_state.ToList();
ddl1.DataValueField = "StateId";
ddl1.DataTextField = "State";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList ddl1 = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl1.NamingContainer;
if (row != null)
{
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList2");
ddl2.DataSource = GetDataForSecondDropDownList(Convert.ToInt32(ddl1.SelectedValue));
ddl2.DataTextField = "CityID";
ddl2.DataValueField = "City";
ddl2.DataBind();
}
}
public GetDataForSecondDropDownList(int ID)
{
using (var context = new ABCEntities())
{
var _city = (from u in context.Cities
where u.StateID == ID
select new
{
CityID = u.CityID,
City= u.City
}).Distinct();
}
return; // How do i return this method
}
我有一個如何STATEID傳遞到一個問題方法GetDataForSecondDropDownList()並返回相關數據以上代碼。
請幫幫我。提前感謝你。