我将在GridView控件中实现级联DropDownList。我的代码如下:
网页:
<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 IEnumerable<City> GetDataForSecondDropDownList(int ID) //Getting Error
{
using (var context = new ABCEntities())
{
var _city = (from u in context.Cities
where u.StateID == ID
select new City
{
CityID = u.CityID,
City= u.City
}).Distinct();
return _city;
}
}
我收到一条错误消息:错误:可访问性不一致:返回类型'System.Collections.Generic.IEnumerable'比方法'....... GetDataForSecondDropDownList(int)'
更难访问我该怎么办请帮助我。提前谢谢。
答案 0 :(得分:0)
错误告诉City
类不太容易访问。可能是私人或受保护的。确保您已将其声明为公开,如下所示:
public class City
{
public int CityID {get;set;}
public string City {get;set;}
}