0

我正在做一个项目只是为了添加一些东西,其中之一是当他们按下一行的编辑按钮时在 GridView 上添加一个 DropDownList ......遗憾的是,这些列是在数据库绑定之前在运行时添加的,而不是在 aspx 上页面作为我找到的所有示例,我在这里有这样的:

private void SetColumnsGrid(GridView Grid)
    {
        BoundField Col = new BoundField();//1
        Col.HeaderText = "Name";
        Col.DataField = "Name";
        Col.HeaderStyle.Width = Unit.Pixel(100);
        Col.ReadOnly = true;
        Grid.Columns.Add(Col);

        Col = new BoundField(); //2
        Col.HeaderText = "User Type";
        Col.DataField = "UserType";
        Col.HeaderStyle.Width = Unit.Pixel(100);
        Grid.Columns.Add(Col);

        //Is ddl spected to be here as the TemplateField with the EditItemTemplate?
}

那么,我该怎么做呢?我只是找不到正确的方法。我应该处理哪些事件?

非常感谢

4

1 回答 1

1

您可以使用几个选项。一种是使用模板,另一种是在创建行时手动添加控件。模板示例(这使用了一个复选框,但可以轻松切换):

Public Class CheckBoxTemplate
    Implements ITemplate   

    Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
        Dim cb As CheckBox = New CheckBox()
        cb.ID = "someId"
        cb.AutoPostBack = True

        container.Controls.Add(cb)


    End Sub
End Class

在您创建 gridview 控件的应用代码中:

    Dim gv As New GridView
    With gv
        .ID = "myGridView"
        .AutoGenerateColumns = False
        .DataKeyNames = New String() {"somePKID"}
        .GridLines = GridLines.Both
        .AllowSorting = False
        .AllowPaging = False
        .PageSize = numRows
        .Width = tableWidth
        .BorderColor = Drawing.ColorTranslator.FromHtml("#808080")
        .PagerSettings.Mode = PagerButtons.NextPrevious
        .PagerSettings.NextPageText = "Next"
        .PagerSettings.PreviousPageText = "Prev"
        .HeaderStyle.CssClass = foundUserHeadStyle
        .RowStyle.CssClass = foundUserEvenRows
        .AlternatingRowStyle.CssClass = foundUserOddRows
        .Columns.Clear()

        Dim SelectUserTF As New TemplateField
        With SelectUserTF
            .HeaderText = "Add"
            .ItemStyle.Wrap = False
            .ItemTemplate = New CheckBoxTemplate()
        End With
       .Columns.Add(SelectUserTF)

   End With

另一种选择是在创建行事件中执行此操作:

     Protected Sub gv_rowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles myGridView.RowCreated
    Try
        Dim myDDL As New DropDownList
        Dim myCollection As New ListItemCollection
        With myCollection
            Dim newItem As New ListItem
            newItem.Text = "item 1"
            newItem.Value = "1"

            .Add(newItem)
        End With
        e.Row.Cells(0).Controls.Add(myDDL)
  Catch ex As Exception

    Finally

    End Try
end sub

让我知道这是否有帮助或您对此有疑问。

于 2013-03-27T11:26:50.000 回答