There are certain scenarios that we need to combine an AutoGenerated Columns with TemplateField Columns or even BoundField Columns in the GridView. As we all know, by default the GridView will automatically display all the AutoGenerated Columns to the rightmost column of the GridView. Consider this example below:
Assuming that we have this GridView markup below:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button A" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Button B" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note: By default the
AutoGenerateColumns property of GridView is set to TRUE, so we don't need to set it manually in the GridView.
Now lets bind the GridView with data from the database. The code would look something like this:
private string GetConnectionString(){
//Where MYDBConnection is the connetion string that was set up in the web config file
return System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
}
private void BindGridView(){
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT Top(5)* FROM Customers";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
protected void Page_Load(object sender, EventArgs e){
if (!Page.IsPostBack){
BindGridView();
}
}
Running the code above will give us this output in the page:
As expected, the columns for TemplateFields (with red box) will be placed at the leftmost columns in the GridView and the AutoGenerate Columns will be rendered at the rightmost columns after the TemplateFields.
The Solution:
In order to move those AutoGenerate Columns to the leftmost columns of the GridView then we can do some server side manipulations at the RowCreated event of GridView.
Check this code block below:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e){
GridViewRow row = e.Row;
// Intitialize TableCell list
List<TableCell> columns = new List<TableCell>();
foreach (DataControlField column in GridView1.Columns)
{
//Get the first Cell /Column
TableCell cell = row.Cells[0];
// Then Remove it after
row.Cells.Remove(cell);
//And Add it to the List Collections
columns.Add(cell);
}
// Add cells
row.Cells.AddRange(columns.ToArray());
}
Running the code above will give us this output below:
As you can see, the AutoGenerated Columns are being move to the leftmost part of the GridView columns.
That's it! Hope you will find this example useful!