获取"指定的参数超出了有效值的范围。参数名称:"

时间:2017-07-24 23:07:27

标签: c# asp.net repeater

我知道在几个帖子上有很多这个标题,但浏览了一些帖子,我没有找到任何帮助我的问题。

我正在尝试在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();

当我运行它时,我收到以下错误消息:

指定的参数超出了有效值的范围。  参数名称:index

在以下一行:

DropDownList ddl =(DropDownList)Repeater2.Controls [Repeater2.Controls.Count - 1] .FindControl(" ddlstate");

任何想法如何解决这个问题?

更新

     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();

1 个答案:

答案 0 :(得分:1)

由于Repeater是基于模板的控件,因此您应该Find DropDownList并在ItemDataBound事件中填充它。 所以你可以这样做:

DataTable table;

protected void Page_Load(object sender, EventArgs e)
{
    //We query the DB only once in the Page Load
    string sSQL = "Select stateID, sateName from Mytable ORDER By stateName ASC";
    SqlCommand cmd6 = new SqlCommand(sSQL, con);
    con.Open();
    table = new DataTable();
    table.Load(cmd6.ExecuteReader());

}

//We load the DropDownList in the event
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var ddl = (DropDownList)e.Item.FindControl("ddlID");
    ddl.DataSource = table;
    ddl.DataTextField = "stateName";
    ddl.DataValueField = "stateID";
    ddl.DataBind();

}