2013-10-23 81 views
1

我對ASP.NET非常陌生,而且一般都是編程。我有一個GridView,我在RowDataBound事件的編輯中添加了一個DropDownList。現有的控件是隻讀的,並且不會在編輯時顯示。如何從RowUpdating事件中動態添加到GridView中的DropDownList中檢索值?

protected void GridViewVehicles_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     if (e.Row.RowState == DataControlRowState.Edit) 
     { 
      DropDownList ddlVehicles = GetVehicles(); 
      string make = e.Row.Cells[9].Text; 
      ddlVehicles.Items.FindByText(reportsTo).Selected = true; 
      e.Row.Cells[10].Controls.Add(ddlVehicles); 
     } 
    } 
}  

問題是,我似乎無法訪問RowUpdating事件中DropDownList的選定值。該表單元格似乎有一個控件計數爲0.以下引發和參數超出範圍異常。

protected void GridViewEmployees_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{ 
    string vehicle = ((DropDownList)(row.Cells[10].Controls[0])).SelectedValue; 
} 

在Chrome調試器,我看到正確的價值被張貼,但我只是無法弄清楚如何訪問它。

我讀過,它可能可以使用DropDownList的OnSelectedIndexChanged事件並將值存儲在ViewState中,但我一直有困難。

任何指導如何最好的進行將不勝感激。提前致謝!

+0

它看起來像我可以用Request.Forms.GetValues(),我發現這裏訪問值:http://www.aspsnippets.com/articles/creating -dynamic-dropdownlist-controls-in-asp.net.aspx – dan55

回答

1

看起來方法GetVehicles()正在動態創建下拉列表,因爲您要將下拉列表添加到第二個if語句最後一行的Controls集合中。

當您動態創建控件時,必須在每次回發時重新創建它們。

取而代之,將下拉控件放在EditItemTemplate之內,然後使用FindControl方法找到該控件,並將其填充到代碼後面,就像您現在正在做的那樣。

這裏是GridView控件定義的例子:

<asp:GridView runat="server" ID="GridViewVehicles" OnRowDataBound="GridViewVehicles_RowDataBound" OnRowUpdating="GridViewVehicles_RowUpdating"> 
     <Columns> 
      <asp:TemplateField> 
       <ItemTemplate> 
        <!-- Text of selected drop-down item -->  
       </ItemTemplate> 
       <EditItemTemplate> 
        <asp:DropDownList runat="server" ID="ddlVehicles" /> 
       </EditItemTemplate> 
      </asp:TemplateField> 

     </Columns> 
    </asp:GridView> 

和代碼隱藏:

protected void GridViewVehicles_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 
      if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit) 
      { 
       //Get the drop-down datasource and perform databinding 
      } 
     } 

     protected void GridViewVehicles_RowUpdating(object sender, GridViewUpdateEventArgs e) 
     { 
      DropDownList ddlVehicles = GridViewVehicles.Rows[e.RowIndex].FindControl("ddlVehicles") as DropDownList; 

      if (ddlVehicles != null) 
      { 
       string selectedValue = ddlVehicles.SelectedValue; 
      } 
     } 

希望它能幫助!

問候,

烏羅什

+0

謝謝!我認爲這樣做。 – dan55

相關問題