我正在使用Datalist来显示国家/地区列出每个记录,其中Gridview包含状态列表,每个州都有一个城市下拉列表。我使用隐藏字段来获取国家/地区的ID,以通过在隐藏字段中使用Eval(“C_ID”)来检索每条记录的状态名称。但它引发了ArgumentOutOfRangeException。我无法知道我做错了什么。 以下是Datalist的代码:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" onitemdatabound="DataList1_ItemDataBound" >
<ItemTemplate>
<table border="1px">
<tr>
<td>
<%#Eval("C_Name") %><br />
<asp:HiddenField ID="HiddenField1" Value='<%#Eval("C_ID") %>' runat="server" />
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="State Cities">
<ItemTemplate >
<asp:CheckBox ID="CheckBox1" runat="server" />
<%#Eval("S_Name") %>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
这就是背后的代码:
public partial class AdvancedTable : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from Country", con);
con.Open();
da.Fill(ds, "Country");
con.Close();
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = new SqlCommand("select * from State where C_ID='"+((HiddenField)DataList1.Items[e.Item.ItemIndex].FindControl("HiddenField1")).Value+"'",con);
con.Open();
da2.Fill(ds, "State");
con.Close();
((GridView)e.Item.FindControl("GridView1")).DataSource = ds.Tables["State"];
((GridView)e.Item.FindControl("GridView1")).DataBind();
}
}
答案 0 :(得分:0)
相反,您可以执行以下操作:
<asp:DropDownList ID="DropDownList1" runat="server" DataSource="<%# GetList((int)Eval("C_ID"))%>">
</asp:DropDownList>
代码背后
protected DataTable GetList(int id){ }
答案 1 :(得分:0)
也许,而不是DataList1.Items[e.Item.ItemIndex].FindControl("HiddenField1")
只需使用e.Item.FindControl("HiddenField1")