繁体   English   中英

得到“指定的参数超出有效值范围。 参数名称:”

[英]Getting “Specified argument was out of the range of valid values. Parameter name:”

我知道几个帖子上都有很多这样的标题,但是浏览了其中的一些帖子后,我发现我的问题没有任何帮助。

我正在尝试在Repeater控件中构建一个下拉列表,该列表会动态填充数据库中的数据。

这是我正在使用的代码:

//标记

州:

//代码文件

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

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

更新:

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM