简体   繁体   中英

Reorder column in Gridview using code behind

i want to switch the columns when the gridview is using ItemTemplate instead of BoundField:

 <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblname" runat="server" Text='name'></asp:Label>
            </ItemTemplate>
</asp:TemplateField>

- Code behind -
     if (Group == "A") { 

                ((BoundField)gv1.Columns[0]).DataField = "name";
                ((BoundField)gv1.Columns[0]).HeaderText = "Name";
                ((BoundField)gv1.Columns[1]).DataField = "gender";
                ((BoundField)gv1.Columns[1]).HeaderText = "Gender";
            }  else   { 

                ((BoundField)gv1.Columns[0]).DataField = "gender";
                ((BoundField)gv1.Columns[0]).HeaderText = "Gender";
                ((BoundField)gv1.Columns[1]).DataField = "name";
                ((BoundField)gv1.Columns[1]).HeaderText = "Name";
            }

i tried "TemplateField abc= new TemplateField()"and .add(), how to specify the new column number position?

Thanks.

i have did it and it worked for me like

Suppose you wanted to move the second column to be the first column you could do

var Move= GridView.Columns[1];
GridView.Columns.RemoveAt(1);
GridView.Columns.Insert(0, move);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM