0

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.

G3n0c1de
  • 139
  • 2
  • 14
  • I think it's better managed with CSS. – CurseStacker Oct 16 '15 at 04:49
  • @CurseStacker, how would I go about giving that one BoundField the correct CSS class or style markup? Again, I can't access it through an ID. Maybe I could give it a custom class, and change what's on the stylesheet from my code behind? After a brief look at google I don't think I can edit a stylesheet from the code behind. – G3n0c1de Oct 16 '15 at 17:54

1 Answers1

2

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.

Community
  • 1
  • 1
G3n0c1de
  • 139
  • 2
  • 14