Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 367, trackbacks - 0

My Links

News

Archives

Image Galleries

Move AutoGenerate Columns at LeftMost Part of the GridView Columns

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!

Print | posted on Wednesday, June 03, 2009 10:23 PM |

Feedback

Gravatar

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns

Very usefull code, however if paging is enabled it breaks. You can check for paging like this;

if (e.Row.RowType != DataControlRowType.Pager)
{
//Put the code here
}

Then the code runs smoothly. Thanks!
6/22/2009 2:52 AM | firkateyn
Gravatar

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns

Hi firkateyn,

Thanks for sharing that.. :)
6/22/2009 3:09 AM | Vinz
Gravatar

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns

thanks. It is very used.
7/28/2009 4:33 PM | prashanth
Gravatar

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns

Thanks, Its very useful.
8/20/2009 5:45 PM | Makbul
Gravatar

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns

Thanks, Its Working.
9/7/2009 10:51 PM | Sami
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: