Saturday, July 6, 2013

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">
    <Columns>
        <asp:BoundField HeaderText="Employee Id" DataField="EmployeeId"/>
        <asp:BoundField HeaderText="First Name" DataField="FirstName"/>
        <asp:BoundField HeaderText="Last Name" DataField="LastName"/>
    </Columns>
</asp:GridView>

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<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;
    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.

image

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

0 comments:

Post a Comment

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

Search This Blog
Loading...
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews