Wrapping text in a gridview to a particular number of characters.

Ndebata
Posted by Ndebata under ASP.NET category on | Points: 40 | Views : 2745
In Aspx page
<form id="form1" runat="server">
<div>
<asp:gridview runat="server" id="gv"></asp:gridview>
</div>
</form>

in .cs file
public partial class _Default : System.Web.UI.Page
{
private int NumberOfCharacterInWrap = 15;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);
if (!IsPostBack)
{
gv.DataSource = GetData();
gv.DataBind();
}
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell item in e.Row.Cells)
{
int stringlen = item.Text.Length;
for (int i = 0; i < stringlen; )
{
if (i > 0)
item.Text = item.Text.Insert(i
+ (Regex.Matches(item.Text, "<br/>").Count * 5)
, "<br/>");
i += NumberOfCharacterInWrap;
}
}
}
}
private DataTable GetData()
{
// generating some sample data here
// In your case you may load data table from database etc.

DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");

dt.Rows.Add(new object[] { "sdshadhadsadjdjajdajdad", "adsjdnasjdnadjkasd" });
dt.Rows.Add(new object[] { "adnnnnnnnnnnnnnnnnnnnnnnnnnsjdnsjndnadndasdjasdhjdasjdasdad", "jhajhdhadhsk" });
dt.Rows.Add(new object[] { "ddhashafnsdfhjshfsyudffnsjfhsfsdfnsdfjsdfs", "fjsjfsdfhsdfnsdfbdssjfsdfhdfdjfbd" });
dt.Rows.Add(new object[] { "dkjdfjdfkdfdjfdfd", "dfdfjdjfdhjfdnfjndjfdhfjdfnjdfhdjfdhfdjfdhfhdj" });
return dt;
}
}

Comments or Responses

Login to post response