动态添加下拉列表在编辑上的datagridviewasp.Net上的代码
本文关键字:datagridviewasp Net 代码 编辑 添加 下拉列表 动态 | 更新日期: 2023-09-27 18:06:08
我正在做一个项目,只是为了添加一些东西,其中一个是在GridView上添加下拉列表,当他们按下一行的编辑按钮…遗憾的是,这些列是在数据库绑定之前的运行时添加的,而不是像我发现的所有示例那样在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?
}
那么,我该怎么做呢?我只是找不到合适的方法。我应该处理哪些事件?
非常感谢
您可以使用几个选项。一种方法是使用模板,另一种方法是在创建行时手动添加控件。模板示例(这使用了一个复选框,但可以很容易地切换):
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
另一个选项是在create row事件中执行此操作:
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
如果有帮助或者有问题请告诉我