Home > .NET > Changing Gridview column width in ASP.NET

Changing Gridview column width in ASP.NET

Today’s tip is a quick but handy one. Gridview is one of the most useful data tools in ASP.NET. By only configuring a datasource using the provided visual “wizard” you will be able to display and even edit your database without writing a single line of SQL or ASP code. Gridviews are  customized easily using the Autoformat feature in the Smart Tag or the property window. However sometimes you do need to write a bit of code to tweak the Gridview’s appearance.

Column’s width are not visually customizable and you need to do this in ASP:

When you drag an drop a Gridview into your project and assign a datasource to it, Visual Studio automatically writes the following ASP code for you which looks like the following code:

<asp:gridview runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ApplicationId" DataSourceID="SqlDataSource2">
    <Columns>
        <asp:BoundField DataField="ApplicationName" HeaderText="ApplicationName" 
            SortExpression="ApplicationName" />
        <asp:BoundField DataField="LoweredApplicationName" 
            HeaderText="LoweredApplicationName" SortExpression="LoweredApplicationName" />
        <asp:BoundField DataField="ApplicationId" HeaderText="ApplicationId" 
            ReadOnly="True" SortExpression="ApplicationId" />
        <asp:BoundField DataField="Description" HeaderText="Description" 
            SortExpression="Description" />
    </Columns>
    </asp:gridview>

Now if you notic all column filed tags are closed. (< asp:… />) We want to add an element to the columns so we need to change the tags to  <asp….></asp…>

Now we can use ItemSyle like this:

<asp:BoundField DataField="ApplicationName" HeaderText="ApplicationName" 
            SortExpression="ApplicationName">
            <ItemStyle Width="40px" />
</asp:BoundField>

This will fix the width of our column to 40 pixels.

Categories: .NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: