动态更改Gridview中的DataField属性

时间:2014-04-16 16:20:16

标签: c# asp.net gridview

我有一个像这样的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? 非常感谢!

1 个答案:

答案 0 :(得分:4)

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

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"