我知道在几个帖子中有很多这个标题,但浏览了其中的一些,我还没有找到任何有关我的问题的帮助。获取“指定的参数超出有效值的范围参数名称:”
我想在Repeater控件中构建一个下拉列表,该下拉列表使用数据库中的数据动态填充。
这里是我使用的代码:
//标记
国家:
//的CodeFile
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconstring"].ToString());
string sSQL = "Select stateID, sateName from Mytable ORDER By stateName ASC";
SqlCommand cmd6 = new SqlCommand(sSQL, con);
con.Open();
SqlDataReader dtrClient = cmd6.ExecuteReader();
DropDownList ddl = (DropDownList)Repeater2.Controls[Repeater2.Controls.Count - 1].FindControl("ddlstate");
ddl.DataSource = dtrClient;
ddl.DataTextField = "stateName";
ddl.DataValueField = "stateID";
ddl.DataBind();
当我运行它,我得到以下错误消息:
指定的参数超出了有效值的范围。 参数名称:
DropDownList的DDL =(DropDownList的)Repeater2.Controls [Repeater2.Controls.Count - 1] .FindControl( “ddlstate”);:上下面的行索引
任何想法如何解决这个问题?
UPDATE:
State: <asp:DropDownList ID="aircraftstate" runat="server" style="width:150px;" AppendDataBoundItems="True">
<asp:ListItem Value="" Selected="True"></asp:ListItem>
</asp:DropDownList>
//We query the DB only once in the Page Load
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ToString());
string sSQL = "Select StateID, StateName from MyTable ORDER By sName ASC";
SqlCommand cmd3 = new SqlCommand(sSQL, con);
con.Open();
table = new DataTable();
table.Load(cmd3.ExecuteReader());
//We load the DropDownList in the event
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var ddl = (DropDownList)e.Item.FindControl("aircraftstate");
ddl.DataSource = table;
ddl.DataTextField = "StateName";
ddl.DataValueField = "StateID";
ddl.DataBind();
偶然的'Repeater2.Controls.Count' 0?你可能试图做'Repeater2.Controls [-1]'。您应该检查一个空的结果集并进行适当的处理。 – itsme86
你检查了我的答案@肯尼? – hardkoded
@kbok。 对不起,延迟回复。我遇到了紧急情况,现在我即将检查它。 虽然看起来很棒。非常感谢。我一直在为这款Repeater下拉列表而苦苦挣扎。很快会回来。 – Kenny