Reputation: 10345
I use a gridview to display data, but sometimes the data is to big to be displayed in a cell. Can I use a method to allow the gridview to display f.e. the first 100 characters of a string?
any help is welcome!
Upvotes: 0
Views: 8274
Reputation: 5337
Create this function
public object TrimString(string input, int length)
{
// return nothing if the string is null
if (String.IsNullOrEmpty(input))
{
return string.Empty;
}
// invalid length submitted
if (length <= 0)
{
length = 100;
}
if (input.Length > length)
{
return input.Substring(0, length) + "...";
}
return input;
}
And you call it from your aspx page like this.
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# TrimString(Eval("CustName").ToString(),100) %>'></asp:Label>
</ItemTemplate>
Upvotes: 0
Reputation: 33867
For an IE only answer, you could use CSS and, as long as you have a set width for the column, set overflow:ellipsis, or overflow:hidden (should work for all browsers), if you don't want the dots.
OK, as per the comment, I haven't used gridviews for a while, but it would be a matter of setting a CSS class for each of those cells and in the class:
trimText
{
overflow:ellipsis;
}
There's also some hacking you can do to get this to display cross browser - some notes here:
http://www.jide.fr/english/emulate-text-overflowellipsis-in-firefox-with-css
Upvotes: 0
Reputation: 2385
You can handle the RowDataBound event of the gridview and cut the text length, like so:
protected void gvNotes_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
int _myColumnIndex = 0; // Substitute your value here
string text = e.Row.Cells[_myColumnIndex].Text;
if (text.Length > 100)
{
e.Row.Cells[_myColumnIndex].Text = text.Substring(0, 100);
}
}
Upvotes: 5