如何从代码后面的GridView中添加TextBox列?
答案 0 :(得分:18)
使用TemplateField并将TextBox添加到ItemTemplate / EditItemTemplate。
<ItemTemplate>
<asp:TextBox ID="TxtFirstName" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
</ItemTemplate>
您可以在aspx上绑定它,如上例或GridView.RowDataBound:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
Dim dr As DataRow = DirectCast(DirectCast(e.Row.DataItem, DataRowView).Row)
Dim TxtFirstName As TextBox = DirectCast(e.Row.FindControl("TxtFirstName"), TextBox )
TxtFirstName.Text = dr("FirstName").ToString
End Select
End Sub
编辑:这是一个关于如何动态添加TemplateField的简单示例:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim txtColumn As New TemplateField
txtColumn.ItemTemplate = New TextColumn
Me.GridView1.Columns.Add(txtColumn)
End If
End Sub
Class TextColumn
Implements ITemplate
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim txt As New TextBox
txt.ID = "MyTextBox"
container.Controls.Add(txt)
End Sub
End Class
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.templatefield.aspx