Adding an ellipsis overflow to a table cell in an ASP.Net GridView.
I ran into an issue of having the name field of a cell in a GridView too long, causing the whole table to mess up my CSS widths.
Now you can't just add this CSS to the desired table cell when using a percentage width:
overflow: hidden;
text-overflow: ellipsis;
The workaround I used for this is to create a div inside the table cell and use the css class for that div to determine it's width using the @media
rule. Here are my examples:
WebPage.aspx
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="TestName" HeaderText="Test name">
<asp:BoundField DataField="TestDesc" HeaderText="Test description">
</Columns>
</asp:GridView>
WebPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
List<Person> people = GetPeople();
DataTable dtPeople = new DataTable();
dtPeople.Columns.Add("TestName");
dtPeople.Columns.Add("TestDesc");
foreach (Person person in people)
{
DataRow drPerson = dtPeople.NewRow();
drPerson["TestName"] = $"<div class='name-overflow'>{person.Name}</div>";
drPerson["TestDesc"] = person.Description;
dtPeople.Rows.Add(drPerson);
}
GridView1.DataSource = dtPeople;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
/* Set the width to a percentage. */
e.Row.Cells[0].Width = new Unit("50%");
/* Properly display the div. */
e.Row.Cells[0].Text = Server.HtmlDecode(e.Row.Cells[0].Text);
}
WebSite.css
@media (max-width: 1000px) {
.name-overflow {
width: 300px;
}
}
@media (max-width: 900px) {
.name-overflow {
width: 260px;
}
}
/* Continue decreasing the max-width and width to get the desired effect. */
.name-overflow {
overflow: hidden;
text-overflow: ellipsis;
}
The @media
tag changes the value of the width of .name-overflow based on the width of the current screen. See more here https://www.w3schools.com/cssref/css3_pr_mediaquery.asp
Subscribe to my newsletter
Read articles from Shayne Kiekebosch directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shayne Kiekebosch
Shayne Kiekebosch
.NET developer specialising in Windows Mixed Reality and Windows forms/services. Utilising Unity I have developed applications for the Microsoft HoloLens 1 and 2 and the Meta Quest 1, 2 and Pro. I was also a senior dev at Blackout Games working on their Rugby Management Game.