Dynamically setting GridView Column width in ASP.Net

I was looking into the forums.asp.net and I have found lots of people was searching about how to set GridView Column Width dynamically. So I thought it will be a good idea to write a blog post about it.

Example(Setting Width Dynamically in ASP.Net):

So let’s take a an example for that. For that I have created a small model Employee class which will have three properties.
public class Employee
    public int  EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

Now let’s create a grid view control for that and then will bind the GridView and dynamically set the GridView Column width. Following is a GridView definition.
<asp:GridView runat="server" ID="employeeGrid" AutoGenerateColumns="False">
        <asp:BoundField HeaderText="Employee Id" DataField="EmployeeId"/>
        <asp:BoundField HeaderText="First Name" DataField="FirstName"/>
        <asp:BoundField HeaderText="Last Name" DataField="LastName"/>

and following a code for binding GridView and Creating a column width dynamically.
protected void Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack)
public void BindGridView()
    var employees = new List<Employee>()
            new Employee() {EmployeeId = 1, FirstName = "Jalpesh", LastName = "Vadgama"},
            new Employee() {EmployeeId = 2, FirstName = "Vishal", LastName  ="Vadgama"},
            new Employee() {EmployeeId = 3, FirstName = "Teerth", LastName = "Vadgama"}

    employeeGrid.DataSource = employees;

public void SetGridViewWidth()
   for (int i = 0; i < employeeGrid.Columns.Count; i++)
       employeeGrid.Columns[i].ItemStyle.Width = 200;

Here in the above code you have seen that I have first created a list of employee and then I have bind that list with employee GridView and then I have applied the column width with ItemStyle.Width property. When you run this code It will look like following.


That’s it. It’s very easy. Stay tuned for more..


Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio