Using Bootstrap In ASP.NET GirdView

Adding bootstrap In ASP.NET GirdView control needs an extra setting to make the GridView to look great. Here we’ll see the extra setting required for the GridView control to use the bootstrap properly.

Consider, you have a simple GridView attached to an SQLDataSource in an aspx file. For example, consider a simple GridView control like this:

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1″>
<Columns>
<asp:BoundField DataField=”CustomerName” HeaderText=”CustomerName” SortExpression=”CustomerName” />
<asp:BoundField DataField=”PhoneNumber” HeaderText=”PhoneNumber” SortExpression=”PhoneNumber” />
<asp:BoundField DataField=”PostalAddressLine1″ HeaderText=”PostalAddressLine1″ SortExpression=”PostalAddressLine1″ />
<asp:BoundField DataField=”PostalAddressLine2″ HeaderText=”PostalAddressLine2″ SortExpression=”PostalAddressLine2″ />
<asp:BoundField DataField=”PostalPostalCode” HeaderText=”PostalPostalCode” SortExpression=”PostalPostalCode” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:WideWorldImportersConnectionString %>” SelectCommand=”SELECT [CustomerName], [PhoneNumber], [PostalAddressLine1], [PostalAddressLine2], [PostalPostalCode] FROM [Sales].[Customers]”>

Bootstrap In ASP.NET GirdView 01

Once compiled the GridView becomes a plain HTML table with rows and columns. But the table does not have a segregated head <thead> and body <tbody> sections. To segregate the table by head and body, you have to add a line of code in the code-behind file. In the code-behind file add the below line of code. (Considering GridView1 is the ID of the GridView). Using the HeaderRow.TableSection property, you can set the location of the table header . This will help the bootstrap class to style the table’s header row and the body rows accordingly.

GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

Bootstrap In ASP.NET GirdView 02

Now add the bootstrap’s css class for table in the GridView control HTML code (<asp:GridView ID=”GridView1″ …………………………….. >).

CssClass=”table table-striped”

Bootstrap In ASP.NET GirdView 03That’s all. You can build and run the project and see how the grid table is formatted. If needed, you can add more bootstrap table classes in the CssClass. Likewise, if you want to make the grid table responsive, wrap the div having the table class with table-responsive class in another div.

Bootstrap In ASP.NET GirdView 04

Related Articles

Reference

  • About GridView control in MSDN.

 

Related Articles & Tools

Leave your thoughts...