Saturday, July 6, 2013

Dynamically setting GridView Column width in ASP.Net

I was looking into the 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..


Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
About Me
My Photo

Full Stack Developer, Blogger, Microsoft Mvp, Mentor, Lifelong learner, 12+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC/Core, C#, Angular,Vue.js and node.js
Subscribe to my blog


My You tube channel- Please Subscribe
Youtube Video Playlist
My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews