Thursday, 29 December 2011

Wrapping column in gridview using CSS style

I used ITemplate to wrap column which gives exact word wrap in column on every browser. One can do it with style also but results are not same in all the browsers. If little difference in result variance in different browser is not an issue then wrapping column using style is much easier than using ITemplate.
Output of wrapping column in gridview using CSS in different browser.


IE 9 - Word Break Chrome - Word Break


Firefox 4 - Word Break Safari- Word Break

Let's see how we can do this.

Step 1: Place a gridview inside form tag.


Step 2: Place below lines of code to bind the data to gridview.


protected void Page_Load(object sender, EventArgs e){ gvWrappinColumn.DataSource = GetData(); gvWrappinColumn.DataBind();}
private DataTable GetData()
{ DataTable dt = new DataTable("Data");
dt.Columns.Add(new DataColumn("ID"));
dt.Columns.Add(new DataColumn("Comments"));
dt.Rows.Add(1,"Testing column of GridView Wrapping1");
dt.Rows.Add(2,"http://www.bing.com/search?q=microtsoft+visual+studio+2010&form=QBLH&qs=n&sk=");
dt.Rows.Add(3,"Testing column of GridView Wrapping2"); return dt;
}

Step 3: Apply word-break:break-all and word-wrap:break-word css in the column. Refer Word-Wrap and Word-Break. To set the minimum width of a column using Unit.

protected void gvWrappinColumn_RowDataBound(object sender, GridViewRowEventArgs e)
{ if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[1].Attributes.Add("style", "word-break:break-all;word-wrap:break-word"); }}

protected void gvWrappinColumn_RowCreated(object sender, GridViewRowEventArgs e)
{ this.gvWrappinColumn.Columns[1].ItemStyle.Width = new Unit(200);
}


Live Demo

This ends the article of wrapping column in gridview using css style.
Like us if you find this post useful. Thanks!

Download Code

No comments:

Post a Comment