Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I got a gridview which needs columns to have dynamic colspans.. which even can I add this and how to add col spans in c# ?
Posted
Comments
Guruprasad.K.Basavaraju 8-Apr-14 14:26pm    
Do you mean which event to add this code/logic ?
j snooze 8-Apr-14 17:34pm    
My guess is(untested) you can do it on the RowDataBound event of the grid.

Its not clear where you need these colspans, but you can check the row type out first
if(e.Row.RowType == DataControlRowType.DataRow) for a data row or
DataControlRowType.HeaderRow for a header row...you get the idea.

Once you are on the row you need the colspan on try this
e.Row.Cells[0].Attributes.Add("colspan", "3");

1 solution

C#
protected void EmployeeGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //Creating a gridview object            
        GridView objGridView = (GridView)sender;
 
        //Creating a gridview row object
        GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
 
        //Creating a table cell object
        TableCell objtablecell = new TableCell();
 
        #region Merge cells
 
        //Add a blank cell at the first three cell headers
        //This can be achieved by making the colspan property of the table cell object as 3
        // and the text property of the table cell object will be blank
        //Henceforth, add the table cell object to the grid view row object
        AddMergedCells(objgridviewrow, objtablecell, 3, "Employee Detail", System.Drawing.Color.LightGreen.Name);
 
        //Merge columns d,e (i.e.Address, City, Region, Postal Code, Country) under the column name "Address Details"
        //This can be achieved by making the colspan property of the table cell object as 2
        //and setting it's text to "Address Details" 
        //Henceforth, add the table cell object to the grid view row object
        AddMergedCells(objgridviewrow, objtablecell, 5, "Address Details", System.Drawing.Color.LightSkyBlue.Name);
 
        //Lastly add the gridrow object to the gridview object at the 0th position
        //Because,the header row position is 0.
        objGridView.Controls[0].Controls.AddAt(0, objgridviewrow);
 
        #endregion
    }
}
 
Share this answer
 
v2
Comments
Maciej Los 9-Apr-14 1:44am    
Use text formatting!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900