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. 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.
and following a code for binding GridView and Creating a column width dynamically.
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindGridView(); SetGridViewWidth(); } } public void BindGridView() { var employees = new List() { 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; employeeGrid.DataBind(); } 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..