2013-06-19 60 views
1

我已經創建了一個從OracleReader填充的GridView。數據包含一個人的名字和姓氏。這部分工作正常。DropDownList自動生成的GridView行

我想添加一個DropDownList作爲第三列,它將有一個單獨的查詢的數據源。我遇到的問題是在代碼後面訪問DropDownList。另外,我將如何訪問每個動態創建的DropDown?

<asp:GridView ID="GridView_People" runat="server" emptydatatext="Make selections above"> 
       <Columns> 
        <asp:TemplateField> 
         <ItemTemplate> 
          <asp:DropDownList ID="DropDown_features" runat="server"> 
          </asp:DropDownList> 
         </ItemTemplate> 
        </asp:TemplateField> 
       </Columns> 
       </asp:GridView> 

而後面的代碼,其填充上點擊一個按鈕在GridView(這一切工作正常,目前)

Protected Sub Button_Submit_Click(sender As Object, e As System.EventArgs) Handles Button_Submit.Click 
    Dim Conn As OracleConnection 
    Dim Cmd As OracleCommand 
    Dim Reader As OracleDataReader 

    Conn = New OracleConnection(--CONNECTIONSTRING--) 

    Dim sqlString As String = "select first, last from TABLE" 
    Cmd = New OracleCommand(sqlString) 

    Cmd.Connection = Conn 
    Cmd.CommandType = Data.CommandType.Text 
    Try 
     Conn.Open() 

     Reader = Cmd.ExecuteReader() 

     GridView_People.DataSource = Reader 

     GridView_People.DataBind() 
    Catch ex As Exception 
    Finally 

    End Try 
    Conn.Close() 
    Conn.Dispose() 
End Sub 

我想在後面的代碼GridView_RowCreated事件訪問DropDown_features,但我不能夠訪問下拉菜單。有任何想法嗎?

回答

2

GridView RowDataBound事件是您要訪問連接到網格中的單個項目的位置,因爲它們被綁定到網格。

protected void GridView_People_RowDataBound(object sender, GridViewRowEventArgs e) 
{    
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Find the particular drop down list for this row 
     DropDownList ddl = (DropDownList)e.Row.FindControl("DropDown_features"); 

     // Go get data and do whatever you need to do to the drop down list 
    } 
} 

注意:您需要在標記添加屬性的RowDataBound事件對你的GridView,像這樣:

onrowdatabound="GridView_People_RowDataBound" 
+0

+1的一個很好的答案。在VB.Net中,他可以選擇使用句柄GridView_People.RowDataBound,而不是在.Aspx/.Ascx標記中連接方法。 – N0Alias

+0

謝謝!這對我有效。我用Handle GridView_People.RowDataBound。 –

+0

作爲一個快速跟進,我將如何創建和使用基於ddl選擇的事件? –