havin havin - 21 days ago 10
Vb.net Question

Grid View Dynamically Generated Column

I have Grid View which is dynamically binded with datatables.

I had to add in the last column a command field AAddOn

When trying like below method..AAddOn is displayed at first..

How can we display the command field at the last..

<asp:GridView ID="AGridView" runat="server" AutoGenerateColumns="true" style="table-layout:fixed;" Width="2000px" RowStyle-HorizontalAlign="Left">
<EmptyDataTemplate>
&nbsp;
</EmptyDataTemplate>
<asp:CommandField ShowEditButton="True" ItemStyle-Width="80px" EditText="Edit Add On">
<ItemStyle Font-Bold="true" Font-Size="Small" />
<HeaderStyle CssClass="AAddOn" />
</asp:CommandField>
</asp:GridView>

Answer

For gridview, defined columns always render first then the auto generated columns render on the right side. To move auto generated columns to left side, you need RowCreated event. There you can manipulate the order of columns as required. You can use below code.

protected void AGridView_RowCreated(object sender, GridViewRowEventArgs e){
        List<TableCell> cellColumns = new List<TableCell>();
        foreach (DataControlField column in GridView1.Columns)
        {
            TableCell cell = e.Row.Cells[0];
            e.Row.Cells.Remove(cell);
            cellColumns.Add(cell);
        }

        e.Row.Cells.AddRange(cellColumns .ToArray());
}
Comments