簡體   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