I have a gridview
with both autogenerated columns
and template field
.
I am using GridView.RowCreated
to move my template field to the rightmost side. However, what I need to do is to put it in between HOUR
column and NAME
column.
Is it possible to insert the template field column in between auto-generated columns?
VB.NET
Dim dt As New DataTable()
dt.Columns.Add("Date", GetType(String))
dt.Columns.Add("Hour", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Status", GetType(String))
'fill table
GridView1.DataSource = dt
GridView1.DataBind()
RowCreated code
Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated
Dim row As GridViewRow = e.Row
' Intitialize TableCell list
Dim columns As New List(Of TableCell)()
For Each column As DataControlField In GridView1.Columns
'Get the first Cell /Column
Dim cell As TableCell = row.Cells(0)
' Then Remove it after
row.Cells.Remove(cell)
'And Add it to the List Collections
columns.Add(cell)
Next
row.Cells.AddRange(columns.ToArray())
End Sub
ASPX
<asp:GridView ID="GridView1" runat="server" CssClass="Grid">
<RowStyle Font-Bold="False" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Control" ShowHeader="True" Visible="True"
ItemStyle-HorizontalAlign="Center">
<HeaderTemplate> View </HeaderTemplate>
<ItemTemplate>
<asp:ImageButton ID="B_SHOW" runat="server" ImageUrl="~/MA/Images and Icons/zoom-icon.png" Width="22px" Height="22px" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' CommandName="EXECUTE_QUERY"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can arrange the Columns of a GridView in any order.
Use the CloneFields()
method to create a copy of your Columns. After that clear the GridView's Column collection and re-add the Columns in required order.
Dim columnsCollection As DataControlFieldCollection =
GridView1.Columns.CloneFields()
GridView1.Columns.Clear()
' Now add the Columns one by one in any order
' add 3rd column as the FIRST Column
GridView1.Columns.Add(columnsCollection(3))
' Add 7th Column as Second Column
GridView1.Columns.Add(columnsCollection(7))
You can also use Insert()
Method, if need be::
GridView1.Columns.Insert(0, columnsCollection(3))