gymcode gymcode - 9 months ago 49
C# Question

ASP.NET Setting width of DataBound column in GridView

I have a GridView which uses BoundField for columns. I am trying to set a maxwidth for my


I have tried many many ways but non of them work. Below is the code for my GridView :

<asp:GridView ID="GridView1" AutoGenerateEditButton="True"
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"

<asp:BoundField HeaderText="UserId"

<asp:BoundField HeaderText="Username"

<asp:BoundField HeaderText="UserInfo"


Looking for suggestions on how I can set the width of a specific column, which is my

Answer Source

I did a small demo for you. Demonstrating how to display long text.

In this example there is a column Name which may contain very long text. The boundField will display all content in a table cell and therefore the cell will expand as needed (because of the content)

The TemplateField will also be rendered as a cell BUT it contains a div which limits the width of any contet to eg 40px. So this column will have some kind of max-width!

    <asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
            <asp:BoundField HeaderText="ID" DataField="ID" />
            <asp:BoundField HeaderText="Name (long)" DataField="Name">
                <ItemStyle Width="40px"></ItemStyle>
            <asp:TemplateField HeaderText="Name (short)">
                    <div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
                        <%# Eval("Name") %>

enter image description here

Here is my demo codeBehind

 public partial class gridViewLongText : System.Web.UI.Page
     protected void Page_Load(object sender, EventArgs e)
         #region init and bind data
         List<Person> list = new List<Person>();
         list.Add(new Person(1, "Sam"));
         list.Add(new Person(2, "Max"));
         list.Add(new Person(3, "Dave"));
         list.Add(new Person(4, "TabularasaVeryLongName"));
         gvPersons.DataSource = list;

 public class Person
     public int ID { get; set; }
     public string Name { get; set; }

     public Person(int _ID, string _Name)
         ID = _ID;
         Name = _Name;