asp.net – 以编程方式将Textbox TemplateField列添加到GridView

前端之家收集整理的这篇文章主要介绍了asp.net – 以编程方式将Textbox TemplateField列添加到GridView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何从代码后面向GridView添加TextBox列?

解决方法

使用 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

原文链接:https://www.f2er.com/aspnet/247745.html

猜你在找的asp.Net相关文章