Reputation: 139
I've got an asp.net GridView and within it a few BoundFields.
<asp:BoundField ReadOnly="True" HeaderText="ID" DataField="ID" SortExpression="ID"></asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="Description" DataField="description" ItemStyle-Wrap="true" ItemStyle-Width="300px" SortExpression="ID"></asp:BoundField>
The text within the description field can be of any length, so for right now I've set the column to just be 300px wide, and wrap the text when necessary.
But what I'd like to implement is where the width is automatically set, like in a normal BoundField up until it reaches 300px in width. After that I'd like it to wrap around.
I thought of trying to implement this during the DataBound event, where I can look at the length of every string that's being added to the table. If it reaches a certain length, I'd add the ItemStyle-Width property to the BoundField.
The problem is that BoundFields aren't given ID's so I can't do the normal way of changing properties in the code behind. I figure it's possible to get at these properties by going through the GridView's ID, but I'm not sure where to add the property.
Upvotes: 0
Views: 2399
Reputation: 139
I figured it out.
I ended up measuring the width of the string using the font and size of the text.
I found an especially helpful link here. The helper class made it easy to generate a SizeF
object. I made a custom CSS class with width: 300px
called width300px.
Here's my code behind:
protected void myGridViewRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Font stringFont = new Font("Times New Roman", 12);
SizeF stringSize = new SizeF();
string description = e.Row.Cells[1].Text;
stringSize = GraphicsHelper.MeasureString(description, stringFont);
if (stringSize.Width > 300)
{
gridViewWallsList.Columns[2].ItemStyle.CssClass = "width300px";
}
}
}
The most important part was getting at the ItemStyle
property of the column. Without an ID I'm going to have to remember to change the column index if I add more columns before it, but this works.
Upvotes: 2