在代码上的DataGridView asp.Net上动态添加DropDownList

时间:2013-03-27 09:27:51

标签: c# asp.net gridview drop-down-menu

我正在处理一个项目只是为了添加一些东西,其中一个就是当他们按下一行的编辑按钮时在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?
}

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

非常感谢

1 个答案:

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

如果这有帮助,或者您对此有疑问,请告诉我。