Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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!

 

Posted on Wednesday, June 3, 2009 10:23 PM ADO.NET , ASP.NET , C# , Tips&Tricks , GridView | Back to top


Comments on this post: Move AutoGenerate Columns at LeftMost Part of the GridView Columns

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
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!
Left by firkateyn on Jun 22, 2009 2:52 AM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
thanks. It is very used.
Left by prashanth on Jul 28, 2009 4:33 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Thanks, Its very useful.
Left by Makbul on Aug 20, 2009 5:45 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Thanks, Its Working.
Left by Sami on Sep 07, 2009 10:51 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
thanks, very proper example.
Left by punit belani on Aug 13, 2010 6:35 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Thanks, Good Example
Left by Smita on Aug 24, 2010 2:46 AM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Perfect.. what I was looking for. Thanks a lot, you saved my day!
Left by Bhavna on Sep 16, 2010 4:17 AM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
thanks for the example is very good. I have a question, it is possible to move to another place on the grid than the last?
Left by carlos on Feb 25, 2011 3:58 AM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
I'd like to thank you for this wonderful example. I know many people have probably visited this site and not posted their thanks, so from everyone you have benefited - THANK YOU!!!
Left by Chris on Apr 08, 2011 9:22 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
heyyy thanks code is very usefull,, but can u tell me how can i move only one template field to left most of gridview ??? i tried to changed column num bt its not working...

thanks ...
Left by dev pandya on May 08, 2011 6:39 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
None of this is necessary. Just click the smart tag in the grid view, select Edit Columns and under CommandField you will find "Edit, Update, Cancel". Add that and move around as you please :)
Left by Ranhiru Cooray on Aug 16, 2011 7:58 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
@Ranhiru Cooray,

Have you tried that with AutoGenerateColumns set to TRUE? =}
Left by Vinz on Aug 17, 2011 3:24 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Nice One Really useful
Left by Anand on Nov 08, 2011 3:46 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Thanks a lot ....
Left by Somak on Jan 13, 2012 7:43 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Thanks, Its very useful, but I it's not working with paging
any idea ?
Left by khalid on Feb 22, 2012 2:47 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Hi, Thanks for the info

Code is Working fine but while generating the grid values from data grid using dridview_selectedindexchange(), follwing error is displaying.

"Index was out of range. Must be non-negative and less than the size of the collection".

Here i am trying to generate to text box like this :
txtProjectName.Text=gvProjectDetail.SelectedRow.Cells[0].Text;
txtProjectStartDate.Text = gvProjectDetail.SelectedRow.Cells[1].Text;
txtProjectEndDate.Text = gvProjectDetail.SelectedRow.Cells[2].Text;
ddlYear.Text = gvProjectDetail.SelectedRow.Cells[4].Text;....etc
Left by Vijai Bharath on Mar 08, 2012 5:10 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
hi,,, i just want to know how did you use the code behind? i mean what property did you add to the data grid view in order for it to use the function..thanks
Left by Albert Perea on Jul 12, 2012 4:04 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
very nice code
Left by Suvasish on Aug 26, 2012 12:06 AM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Its very useful,thank u........
Left by sk on Oct 17, 2012 8:35 PM

# re: Move AutoGenerate Columns at LeftMost Part of the GridView Columns
Requesting Gravatar...
Perfect. I was looking for this.
Thank you
Left by Andy on Nov 16, 2012 11:39 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net