动态更改Gridview中的DataField属性

本文关键字:DataField 属性 中的 Gridview 动态 | 更新日期: 2023-09-27 17:58:48

我有一个这样的GridView:

<asp:GridView ID="GridViewAllPeopleEditMode" runat="server" 
    AutoGenerateColumns="false"
    AutoGenerateEditButton="true" 
    AllowPaging="true" 
    PageSize="20"
    OnRowEditing="GridViewAllPeopleEditMode_RowEditing" 
    OnRowCancelingEdit="GridViewAllPeopleEditMode_RowCancelingEdit" 
    OnRowUpdating="GridViewAllPeopleEditMode_RowUpdating"
    OnPageIndexChanging="GridViewAllPeopleEditMode_PageIndexChanging"> 
    <Columns>
        <asp:BoundField DataField="id" HeaderText="BusinessEntityID" ReadOnly="true"/>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName"/>
        <asp:BoundField DataField="MiddleName" HeaderText="MiddleName"/>
        <asp:BoundField DataField="LastName" HeaderText="LastName"/>
    </Columns>
</asp:GridView>

我希望page_load在设置DataSource()/DataBind()之前先设置DataField属性,而不是自己在.aspx页面中编写它们。

有可能做到这一点吗?或者我必须更改BoundFields吗?非常感谢!

动态更改Gridview中的DataField属性

您可以在代码端中这样使用

C#
BoundField field = (BoundField)this.GridViewAllPeopleEditMode.Columns[0];
field.DataField = "To";
VB
Dim field As BoundField = DirectCast(Me.GridViewAllPeopleEditMode.Columns(0), BoundField)
field.DataField = "To"