自动生成的GridView行中的DropDownList

时间:2013-06-19 15:22:02

标签: asp.net vb.net

我创建了一个从OracleReader填充的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,但我无法访问下拉列表。有什么想法吗?

1 个答案:

答案 0 :(得分: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
    }
}

注意:您需要在GridView的标记中添加RowDataBound事件的属性,如下所示:

onrowdatabound="GridView_People_RowDataBound"