J_J
J_J

Reputation: 45

Change DataField Attribute in a Gridview dynamically

I have a GridView like this:

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

I want the page_load to set the DataField attributes before setting the DataSource()/DataBind(), instead of writing them by myself in the .aspx page.

Is it possible to do that, or do I have to change the BoundFields? Thanks a lot!

Upvotes: 1

Views: 8082

Answers (1)

Pragnesh Khalas
Pragnesh Khalas

Reputation: 2898

You can use like this in code side

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"

Upvotes: 5

Related Questions