Thursday, December 22

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.
      <asp:GridView ID="gvWrappinColumn" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvWrappinColumn_RowDataBound" OnRowCreated
<HeaderStyle HorizontalAlign="Left" Height="20px" BackColor="#880015" ForeColor="#ffffff" Font-Bold="true" Font-Size=".75em" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"  />
                     <Columns>                               <asp:BoundField HeaderText="Id" DataField="ID"/>                                <asp:BoundField HeaderText="Comments" DataField="Comments"/>                         </Columns>            <AlternatingRowStyle BackColor="#eeeeee" />         </asp:GridView>   </div>

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(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!
Shibashish mohanty
Download Code

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

shibashish mohanty