2017-07-24 98 views
0

我知道在幾個帖子中有很多這個標題,但瀏覽了其中的一些,我還沒有找到任何有關我的問題的幫助。獲取「指定的參數超出有效值的範圍參數名稱:」

我想在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(); 
+0

偶然的'Repeater2.Controls.Count' 0?你可能試圖做'Repeater2.Controls [-1]'。您應該檢查一個空的結果集並進行適當的處​​理。 – itsme86

+0

你檢查了我的答案@肯尼? – hardkoded

+0

@kbok。 對不起,延遲迴復。我遇到了緊急情況,現在我即將檢查它。 雖然看起來很棒。非常感謝。我一直在爲這款Repeater下拉列表而苦苦掙扎。很快會回來。 – Kenny

回答

1

爲轉發器是一個基於模板的控制,你應該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(); 

} 
+0

非常感謝。短而甜蜜的解決方案。 – Kenny

相關問題