Navigation

Search

Categories

On this page

and tags in Gridview
How to pass more than one parameter in a HyperLinkField
ASP.NET 4.0 and the Entity Framework – Gridview
Including
Filtering a Gridview With a Dropdownlist
Search and Highlight a GridView Using jQuery
Using jQuery to Hide Rows or Columns in a Gridview
Exporting Data From a Gridview to Excel
Using jQuery to Hide Table Rows in a Gridview
How to Delete Multiple Rows in a Gridview
GridView Paging using ASP.NET AJAX Slider Extender
Exporting Data from a Gridview to Excel
Using the Gridview.Sorting and Gridview.Sorted Events
Using a DetailsView with a Gridview control
Updating and Editing a Gridview
Client Confirmation to a GridView Delete

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 240
This Year: 46
This Month: 3
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Wednesday, July 07, 2010
Wednesday, July 07, 2010 9:34:17 PM (GMT Daylight Time, UTC+01:00) ( Gridview )

<
asp:HyperLinkField HeaderText="" Text="View" DataNavigateUrlFields="list_id,ListName" DataNavigateUrlFormatString="list.view.aspx?list_id={0}&ListName={1}"> </asp:HyperLinkField>
Comments [0] | | # 
# Wednesday, June 16, 2010
Wednesday, June 16, 2010 4:15:23 PM (GMT Daylight Time, UTC+01:00) ( Entity Framework | Gridview )


This article demonstrates how to view and edit records in a table using the GridView, EntityDataSource, and Validator controls.  The article also demonstrates how to generate an ADO.NET Entity Data Model to update and delete records in a table.

Comments [0] | | # 
# Friday, May 28, 2010
Friday, May 28, 2010 2:13:20 AM (GMT Daylight Time, UTC+01:00) ( Gridview )


By default the Gridview does not use these tags to create its table and often times you will need these elements in client-side scripts:

<table id="myTable"> 
<thead> 
<tr>     
<th>Last Name</th>     
<th>First Name</th>     
<th>Email</th>     
<th>Due</th>     
<tbody> 
<tr>     
<td>Smith</td>     
<td>John</td>     
<td>jsmith@gmail.com</td>     
<td>$50.00</td>     
</tr>
</tobdy>
</table> 
The easiest way to achieve is is to use the page Pre_Render event:
protected void gv_PreRender(object sender, EventArgs e)
{

   if (gv.Rows.Count > 0)
   {
      //Replacing <td> with <th> - just in case
      gv.UseAccessibleHeader = true;
      //Adding the <thead> and <tbody> elements
      gv.HeaderRow.TableSection = TableRowSection.TableHeader;

      //This line can be put if you also have footer, it will add <tfoot> element 
      //If you don't have footer, remove it
      gv.FooterRow.TableSection = TableRowSection.TableFooter;
   }

}
 
Comments [0] | | # 
# Tuesday, May 18, 2010
Tuesday, May 18, 2010 8:58:02 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | ASP.NET AJAX | Gridview )

I was looking for a way to filter the results in a gridview by selecting a value in a dropdownlist and came across this great example

http://blog.evonet.com.au/post/Creating-a-Stylish-looking-Gridview-with-Filtering.aspx

First the CSS

.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, 
Helevetica, sans-serif; color: #303933;} Table.Gridview{border:solid 1px #df5015;} .GridviewTable{border:none} .GridviewTable td{margin-top:0;padding: 0; vertical-align:middle } .GridviewTable tr{color: White; background-color: #df5015; height: 30px; text-align:center} .Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center} .Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;} .Gridview tr{color: Black; background-color: White; text-align:left} :link,:visited { color: #DF4F13; text-decoration:none } Then the .aspx page
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
    <link rel="stylesheet" type="text/css" href="gridview.css" media="all" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <h3>Gridview with Filtering</h3>
            <div class="GridviewDiv">
            <table style="width: 540px" border="0" cellpadding="0" cellspacing="1" class="GridviewTable">
                <tr >
                    <td style="width: 40px;">
                        ID
                    </td>
                    <td style="width: 120px;" >
                        First Name
                    </td>
                    <td style="width: 120px;">
                        Last Name
                    </td>
                    <td style="width: 130px;">
                        Department
                    </td>
                    <td style="width: 130px;">
                        Location
                    </td>
                </tr>
                <tr >
                    <td style="width: 40px;">
                    </td>
                    <td style="width: 120px;">
                    </td>
                    <td style="width: 120px;">
                    </td>
                    <td style="width: 130px;">
                        <asp:DropDownList ID="ddldepartment" DataSourceID="dsPopulateDepartment" AutoPostBack="true"
                            DataValueField="department" runat="server" Width="120px" Font-Size="11px" AppendDataBoundItems="true">
                            <asp:ListItem Text="All" Value="%"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                    <td style="width: 130px;">
                        <asp:DropDownList ID="ddlLocation" DataSourceID="dsPopulateLocation" AutoPostBack="true"
                            DataValueField="location" runat="server" Width="120px" Font-Size="11px" AppendDataBoundItems="true">
                            <asp:ListItem Text="All" Value="%"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td colspan="5">
                        <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                            AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="Gridview">
                            <Columns>
                                <asp:BoundField DataField="id" HeaderText="Sort" SortExpression="id" ItemStyle-Width="40px"
                                    ItemStyle-HorizontalAlign="Center" />
                                <asp:BoundField DataField="FirstName" HeaderText="Sort" SortExpression="FirstName"
                                    ItemStyle-Width="120px" />
                                <asp:BoundField DataField="LastName" HeaderText="Sort" SortExpression="LastName"
                                    ItemStyle-Width="120px" />
                                <asp:BoundField DataField="Department" HeaderText="Sort" SortExpression="Department"
                                    ItemStyle-Width="130px" />
                                <asp:BoundField DataField="Location" HeaderText="Sort" SortExpression="Location"
                                    ItemStyle-Width="130px" />
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
            </table>
            </div>
            <asp:SqlDataSource ID="dsGridview" runat="server" ConnectionString="<%$ ConnectionStrings:EvonetConnectionString %>"
                SelectCommand="SELECT * FROM [T_Employees]" FilterExpression="Department like '{0}%'
                and Location like '{1}%'">
                <FilterParameters>
                    <asp:ControlParameter Name="Department" ControlID="ddldepartment" PropertyName="SelectedValue" />
                    <asp:ControlParameter Name="Location" ControlID="ddllocation" PropertyName="SelectedValue" />
                </FilterParameters>
            </asp:SqlDataSource>
            <asp:SqlDataSource ID="dsPopulateDepartment" runat="server" ConnectionString="<%$ ConnectionStrings:EvonetConnectionString %>"
                SelectCommand="SELECT DISTINCT Department from [T_Employees]"></asp:SqlDataSource>
            <asp:SqlDataSource ID="dsPopulateLocation" runat="server" ConnectionString="<%$ ConnectionStrings:EvonetConnectionString %>"
                SelectCommand="SELECT DISTINCT Location FROM [T_Employees]"></asp:SqlDataSource>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>
Comments [0] | | # 
# Friday, January 15, 2010
Friday, January 15, 2010 9:24:10 PM (GMT Standard Time, UTC+00:00) ( Gridview | jQuery )

 

This cool example allows you to enter some text into a textbox which searches and highlights the results in a Gridview.  Here is a working demo. And another example.

<script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js"></script>

    <script type="text/javascript">
        $(function() {
            var $txtBox = $('input[id$=txtSearch]');
            $txtBox.keyup(function(e) {
            searchText();
        });
        
        function searchText() {
            var $txt = $txtBox.val().toLowerCase();
                $(".grid td").removeClass("highlight");
                if ($txt) {
                $(".grid > tbody > tr > td:not(:has(table, tr))")
                .filter(function() {
                return $(this).text().toLowerCase().indexOf($txt) != -1;
                }).addClass('highlight');
                }
            }
            searchText();
        });
</script>
    
</head>
<body>

<form runat="server">
Enter Text Here: <asp:TextBox ID="txtSearch" runat="server" /><br /><br />

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="false" class="grid" 
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="gray" Font-Bold="True" ForeColor="Black" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

</form>
Comments [0] | | # 
# Friday, December 18, 2009
Friday, December 18, 2009 3:02:10 AM (GMT Standard Time, UTC+00:00) ( Gridview | jQuery )


This is a neat example of how to click on rows in a Gridview to highlight them and click on a keyboard letter to hide/remove the selected rows.

Here is a working demo

 

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
     .highlite {
        background-color: Yellow;
    }
    
    .tableDiv {
    background-color:White;
    font-family: "Lucida Grande", Verdana, Arial; 
    font-size:13px; 
    color:#000000;
    width:460px; 
    margin-left:auto;
    margin-right:auto;
    padding:10px;
    border:solid 1px #c6cfe1;
}

    </style>

    <title>Format Grid</title>
  <script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function() {
            $(".grid > tbody > tr:not(:has(table, th))")
                .css("cursor", "pointer")
                    .click(function() {
                        $(this).toggleClass('highlite');
                });
            $(document).keyup(function(e) {
                var key = (e.keyCode ? e.keyCode : e.charCode);
                if (key == 68) { // D OR d
                    var cnt = $("tr.highlite").length;
                    $("tr.highlite").remove();
                    $("#message")
                        .html("<b>" + cnt + "</b>" + " row(s) hidden");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    
    <div class="tableDiv">
    <h4>Click on the Rows to Highlight them. Press 'd' or 'D' to Remove the Rows</h4><br />
<p id="message"></p>
   
    <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        GridLines="None" class="grid"        
        Runat="server" CellPadding="4" ForeColor="#333333" >        
        </asp:GridView>
    
    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:MyDatabase %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>

To highlight and remove columns, the code isn’t that much different from the code above. See this working demo on how to highlight and remove columns in a gridview.

<script type="text/javascript">
        $(function() {
            $(".grid th")
                .css("cursor", "pointer")
                    .click(function(e) {
                         var $idx = $(this).parent().children().index($(this));
                        $(".grid th:eq(" + $idx + "),.grid tr td:nth-child(" + ($idx + 1) + ")")
                            .toggleClass("highlite");
                    });
                
            $(document).keyup(function(event) {
                var key = event.keyCode || event.charCode || 0;
                if (key == 68) { // D OR d
                    var cnt = $("th.highlite").length;
                    $("td.highlite, th.highlite").remove();
                    $("#message")
                    .html("<b>" + cnt + "</b>" + " column(s) deleted!!");
                }
            });
        });
</script>
Comments [0] | | # 
# Thursday, December 17, 2009
Thursday, December 17, 2009 3:26:57 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )


There are many examples of this online and I’ve posted one myself. When using an updatepanel with your Gridview, it’s common to receive the error message I  "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. " Just setting EnableEventValidation="false" in the page directive won’t work in this case.

<%@ Import Namespace="System.IO" %>

<asp:button id="btnExportExcel" Text="Export to Excel" onclick="ExcelExport" runat="server" />

 Sub ExcelExport(ByVal Source As Object, ByVal E As EventArgs)
        Export("CompanyList.xls", GridView1)
    End Sub

    Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView)
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/ms-excel"
        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        '  Create a form to contain the grid
        Dim table As Table = New Table
        table.GridLines = gv.GridLines
        '  add the header row to the table
        If (Not (gv.HeaderRow) Is Nothing) Then
            PrepareControlForExport(gv.HeaderRow)
            table.Rows.Add(gv.HeaderRow)
        End If
        '  add each of the data rows to the table
        For Each row As GridViewRow In gv.Rows
            PrepareControlForExport(row)
            table.Rows.Add(row)
        Next
        '  add the footer row to the table
        If (Not (gv.FooterRow) Is Nothing) Then
            PrepareControlForExport(gv.FooterRow)
            table.Rows.Add(gv.FooterRow)
        End If
            
        '  render the table into the htmlwriter
        table.RenderControl(htw)
        '  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString)
        HttpContext.Current.Response.End()
    End Sub

    ' Replace any of the contained controls with literals
    Private Shared Sub PrepareControlForExport(ByVal control As Control)
        Dim i As Integer = 0
        Do While (i < control.Controls.Count)
            Dim current As Control = control.Controls(i)
            If (TypeOf current Is LinkButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
            ElseIf (TypeOf current Is ImageButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
            ElseIf (TypeOf current Is HyperLink) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
            ElseIf (TypeOf current Is DropDownList) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
            ElseIf (TypeOf current Is CheckBox) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
                'TODO: Warning!!!, inline IF is not supported ?
            End If
            If current.HasControls Then
                PrepareControlForExport(current)
            End If
            i = (i + 1)
        Loop
    End Sub
Comments [0] | | # 
# Wednesday, September 09, 2009
Wednesday, September 09, 2009 4:26:55 PM (GMT Daylight Time, UTC+01:00) ( CSS | Gridview | jQuery )

 

I’m working on a project which requires users to have the ability to hide rows in a table associated with a certain value.  I checked around and using jQuery seemed to be the best option.   This is a much more elegant approach than doing it server-side.  Here’s what I did.

First, I included a hidden field as a row in my Gridview.  This field is a bit field (true/false) which two CSS classes and one of which is ‘hiddenField’ which makes the field invisible to the user.

<asp:boundfield DataField="InternalOnly" ShowHeader="true" ItemStyle-CssClass="hiddenField internalField" />

CSS code:

.hiddenField {    
    visibility:hidden;
}

Above the Gridview, I included a checkbox with an Id of chkInternal which the user can toggle to hide/show the rows in the Gridview

<input name="chkInternal" id="chkInternal" type="checkbox" />Exclude Non-product fields

Lastly, I use this bit of jQuery code to hide/show the rows in the table. When the chkInternal checkbox is checked, it applies the CSS property display: none to the the entire table row using the jQuery method .parent. It looks for the second CSS class property ‘internalField’. Conversely, when the checkbox chkInternal is not checked, the CSS property display: block is applied to the row making the row visible again. 

<script language="javascript" type="text/javascript">    
$(document).ready(function() {      
      $('#chkInternal').click(
          function() {
          $('.internalField').each(function() {
             if ($("#chkInternal").is(":checked"))
            {
                if ($(this).text() == "True") 
                        $(this).parent().css('display', 'none');                
            }
            else
            {      
                $(this).parent().css('display', 'block');                
            }
        });                 
    });                      
});
</script>
Comments [0] | | # 
# Wednesday, June 24, 2009
Wednesday, June 24, 2009 2:42:26 PM (GMT Daylight Time, UTC+01:00) ( Gridview )


The Gridview provides built-in functionality for deleting rows in a Gridview one at a time but deleting multiple records in batches is usually more efficient.

First create a SqlDataSource and bind the Gridview to it:

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
       <DeleteParameters>
           <asp:Parameter Name="EmployeeID" />
       </DeleteParameters>
</asp:SqlDataSource>

Create a template field inside of the <Columns> of the Gridview:

<asp:TemplateField>
       <ItemTemplate>
             <asp:CheckBox ID="chkRows" runat="server"/>
      </ItemTemplate>
</asp:TemplateField>

The code should now look similar to this.  Notice that the DataKeyNames property is EmployeeID for the Gridview.

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
   <DeleteParameters>
       <asp:Parameter Name="EmployeeID" />
   </DeleteParameters>
</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
   
   <Columns>
      <asp:TemplateField>
          <ItemTemplate>
            <asp:CheckBox ID="cbRows" runat="server"/>
          </ItemTemplate>
       </asp:TemplateField>
 
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
   </Columns>
</asp:GridView>
  
<asp:Button
   ID="btnMultipleRowDelete"
   OnClick="btnMultipleRowDelete_Click"
   runat="server"
   Text="Delete Rows" />

Here’s the code which performs the actual deleting of the records:

Protected Sub btnMultipleRowDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
' Looping through all the rows in the GridView
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("cbRows"), CheckBox) 

'Check if the checkbox is checked. 
If checkbox.Checked Then

'Retreive the Employee ID
Dim employeeID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
'Pass the value of the selected Employee ID to the Delete command.
SqlDataSource1.DeleteParameters("EmployeeID").DefaultValue = employeeID.ToString()
SqlDataSource1.Delete()
End If
Next row
End Sub

Comments [0] | | # 
# Thursday, January 01, 2009
Thursday, January 01, 2009 11:05:23 AM (GMT Standard Time, UTC+00:00) ( ASP.NET AJAX | Gridview )

This code and demonstration is based on this article.

Here is a working demo.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


<script runat="server">
    Protected Sub txtSlide_Changed(ByVal sender As Object, ByVal e As EventArgs)
        Dim txtCurrentPage As TextBox = TryCast(sender, TextBox)
        Dim rowPager As GridViewRow = GridView1.BottomPagerRow
        Dim txtSliderExt As TextBox = CType(rowPager.Cells(0).FindControl("txtSlide"), TextBox)
        GridView1.PageIndex = Int32.Parse(txtSliderExt.Text) - 1
    End Sub

    Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As EventArgs)
        Dim rowPager As GridViewRow = GridView1.BottomPagerRow
        Dim slide As SliderExtender = CType(rowPager.Cells(0).FindControl("ajaxSlider"), SliderExtender)
        slide.Minimum = 1
        slide.Maximum = GridView1.PageCount
        slide.Steps = GridView1.PageCount
    End Sub
</script>

<html>
<head runat="server">
<title></title>
<style type="text/css">
body
{
font: normal 11px auto "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;    
background-color: #ffffff;
color: #4f6b72;       
}
 
th {
font: bold 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 12px;
background: #D5EDEF;
}
 
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
padding: 6px 6px 6px 12px;
color: #4f6b72;
}
 
td.alt
{
background: #F5FAFA;
color: #797268;
}
 
td.boldtd
{
font: bold 13px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background: #D5EDEF;
color: #797268;
}
</style>
</head>
<body>

<form runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AutoGenerateColumns="false" PageSize="3"
DataKeyNames="ID" DataSourceID="SqlDataSource1" OnDataBound="GridView1_DataBound">
<Columns>
    <asp:BoundField DataField="Title" HeaderText="Title" />
    <asp:BoundField DataField="Director" HeaderText="Director" />
    <asp:BoundField DataField="DateReleased" HeaderText="Date Released" DataFormatString="{0:d}" /> 
</Columns>
<PagerTemplate>
    <asp:TextBox ID="txtSlide" runat="server" Text='<%# GridView1.PageIndex + 1 %>' AutoPostBack="true" OnTextChanged="txtSlide_Changed"/>               
    <cc1:SliderExtender ID="ajaxSlider" runat="server" TargetControlID="txtSlide" Orientation="Horizontal"  />
       <asp:Label ID="lblPage" runat="server" Text='<%# "Page " & (GridView1.PageIndex + 1) & " of " & GridView1.PageCount %>' />
       <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                    <ProgressTemplate>
                        <img alt="Loading" src="/images/ajaxicons/loading.gif" />                       
                    </ProgressTemplate>
</asp:UpdateProgress>
    </PagerTemplate>
</asp:GridView>

</ContentTemplate>
</asp:UpdatePanel>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabase%>"
    ProviderName="System.Data.SqlClient" SelectCommand="SELECT [ID], [Title], [Director], [DateReleased] FROM [Movies]">
</asp:SqlDataSource>

</form>

</body>
</html>
Comments [0] | | # 
# Tuesday, September 09, 2008
Tuesday, September 09, 2008 2:34:31 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Gridview )

I've done this many times in the past with other applications using the code below but once I moved the application into a Sharepoint environment coupled with AJAX extensions, I kept receiving the dreaded "RegisterForEventValidation can only be called during Render" error message. 

 

Sub ExcelExport(ByVal Source As Object, ByVal E As EventArgs)                    
            MyGrid.AllowPaging = "False"
            MyGrid.AllowSorting = "False"
            Dim tw As New StringWriter()
            Dim hw As New System.Web.UI.HtmlTextWriter(tw)
            Dim frm As HtmlForm = New HtmlForm()
            Response.ContentType = "application/vnd.ms-excel"
            Response.AddHeader("content-disposition", "attachment;filename=IT.Work.Requests.xls")
            Response.Charset = ""
            EnableViewState = False
            Controls.Add(frm)
            frm.Controls.Add(MyGrid)
            frm.RenderControl(hw)
            Response.Write(tw.ToString())
            Response.End()
            MyGrid.AllowPaging = "True"
            MyGrid.DataBind()
    End Sub

The most common fix for this problem is to set EnableEventValidation="false" in the page directive but this wasn't working for me either. 

Another common suggestion is to use the VerifyRenderingInServerForm method which ensures than a Htmlform control is rendered at the runtime.


Public
Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub 


Finally, which ultimately fixed the problem was Matt Berseth's blog post on exporting data from a gridview to Excel.  The VB version of the code is below.

** Default.aspx **

<%@ Page Language="VB" AutoEventWireup="true"  CodeFile="Default.aspx.vb" Inherits="_Default" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:SqlDataSource 
                ID="sqldsCustomers" runat="server" 
                SelectCommand="select * from dbo.customers" SelectCommandType="Text" 
                ConnectionString="server=PCFRED\SQLEXPRESS;database=northwind;Trusted_Connection=yes;" /> 
            
            <asp:GridView 
                id="gvCustomers" runat="server" 
                AllowPaging="true" AllowSorting="true" PageSize="10" DataSourceID="sqldsCustomers" />
            <asp:Button 
                ID="btnExportGrid" runat="server" 
                Text="Export to Excel" OnClick="BtnExportGrid_Click" />
        </div>
    </form>
</body>
</html>

** Default.aspx.vb **

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Public Class _Default
    Inherits System.Web.UI.Page
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    
    Protected Sub BtnExportGrid_Click(ByVal sender As Object, ByVal args As EventArgs)
        '  pass the grid that for exporting ...
        GridViewExportUtil.Export("Customers.xls", Me.gvCustomers)
    End Sub
End Class

** App_Code/GridviewExportUtil.vb **

Imports System
Imports System.Data
Imports System.Configuration
Imports System.IO
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Public Class GridViewExportUtil

    Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView)
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/ms-excel"
        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        '  Create a form to contain the grid
        Dim table As Table = New Table
        table.GridLines = gv.GridLines
        '  add the header row to the table
        If (Not (gv.HeaderRow) Is Nothing) Then
            GridViewExportUtil.PrepareControlForExport(gv.HeaderRow)
            table.Rows.Add(gv.HeaderRow)
        End If
        '  add each of the data rows to the table
        For Each row As GridViewRow In gv.Rows
            GridViewExportUtil.PrepareControlForExport(row)
            table.Rows.Add(row)
        Next
        '  add the footer row to the table
        If (Not (gv.FooterRow) Is Nothing) Then
            GridViewExportUtil.PrepareControlForExport(gv.FooterRow)
            table.Rows.Add(gv.FooterRow)
        End If
        '  render the table into the htmlwriter
        table.RenderControl(htw)
        '  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString)
        HttpContext.Current.Response.End()
    End Sub

    ' Replace any of the contained controls with literals
    Private Shared Sub PrepareControlForExport(ByVal control As Control)
        Dim i As Integer = 0
        Do While (i < control.Controls.Count)
            Dim current As Control = control.Controls(i)
            If (TypeOf current Is LinkButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
            ElseIf (TypeOf current Is ImageButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
            ElseIf (TypeOf current Is HyperLink) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
            ElseIf (TypeOf current Is DropDownList) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
            ElseIf (TypeOf current Is CheckBox) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
                'TODO: Warning!!!, inline IF is not supported ?
            End If
            If current.HasControls Then
                GridViewExportUtil.PrepareControlForExport(current)
            End If
            i = (i + 1)
        Loop
    End Sub
End Class
Comments [0] | | # 
# Tuesday, April 08, 2008
Tuesday, April 08, 2008 5:53:34 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Gridview )


If you're using a SQLDataSource, it's pretty simple to add sorting to a Gridview.  But often times we need some specific event to occur when we sort a column such as change the text in a label control, add ASC or DESC up and down arrows to indicate how a Gridview is being sorted, databind some other object on the page etc.  Below are two examples - the first one uses the Gridview.Sorting event and the last one uses Gridview.Sorted.

<script runat="server">

  Sub CustomersGridView_Sorting(sender As Object, e As GridViewSortEventArgs)

    ' Cancel the sorting operation if the user attempts
    ' to sort by address.
    If e.SortExpression = "Address" Then

      e.Cancel = True
      Message.Text = "You cannot sort by address."
      SortInformationLabel.Text = ""

    Else

      Message.Text = ""

    End If

  End Sub

  Sub CustomersGridView_Sorted(ByVal sender As Object, ByVal e As EventArgs)

    ' Display the sort expression and sort direction.
    SortInformationLabel.Text = "Sorting by " & _
      CustomersGridView.SortExpression.ToString() & _
      " in " & CustomersGridView.SortDirection.ToString() & _
      " order."

  End Sub

</script>

<html  >
  <head runat="server">
    <title>GridView Sorted and Sorting Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>GridView Sorted and Sorting Example</h3>

      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>

      <br/>

      <asp:label id="SortInformationLabel"
        forecolor="Navy"
        runat="server"/>

      <br/>  

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="true"
        allowpaging="true"
        emptydatatext="No data available." 
        allowsorting="true"
        onsorting="CustomersGridView_Sorting"
        onsorted="CustomersGridView_Sorted"  
        runat="server">

      </asp:gridview>
<asp:sqldatasource .... />
Comments [0] | | # 
# Tuesday, December 11, 2007
Tuesday, December 11, 2007 2:49:34 AM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )


This example shows an example of linking controls together, this time providing a master/details view. The first grid, a GridView, shows the basic details of a product. The second control, a DetailsView is bound to a SqlDataSource, but with the data source having a SelectParameter bound to the SelectedValue property of the first grid. This means that when no row is selected on the first grid, the DetailsView is not shown as there is no data to bind to. Once a row is selected, however, the SelectedValue holds the ProductID and the DetailsView only shows data for that selected product.

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectString %>"
    SelectCommand="SELECT ProductID, ProductName FROM Products" />
    
  <asp:GridView ID="GridView1" runat="server"
    AllowPaging="true" PageSize="5"
    DataKeyNames="ProductID" AutoGenerateColumns="true"
    DataSourceID="SqlDataSource1">
    <Columns>
      <asp:CommandField ShowSelectButton="true" />
    </Columns>
  </asp:GridView>
  
  <br /><br />
  
  <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectString %>"
    DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @ProductID"
    InsertCommand="INSERT INTO [Products] ([ProductName], [SupplierID], [CategoryID], [QuantityPerUnit], [UnitPrice], 
[UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued]) VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit,
@UnitPrice, @UnitsInStock, @UnitsOnOrder, @ReorderLevel, @Discontinued)"
SelectCommand="SELECT Products.ProductID, Products.ProductName, Products.SupplierID, Products.CategoryID,
Products.QuantityPerUnit, Products.UnitPrice, Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel,
Products.Discontinued, Suppliers.CompanyName, Categories.CategoryName FROM Products INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID
WHERE (Products.ProductID = @ProductID)"
UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [SupplierID] = @SupplierID,
[CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice, [UnitsInStock] =
@UnitsInStock, [UnitsOnOrder] = @UnitsOnOrder,
[ReorderLevel] = @ReorderLevel, [Discontinued] = @Discontinued WHERE [ProductID] = @ProductID"
> <DeleteParameters> <asp:Parameter Name="ProductID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="SupplierID" Type="Int32" /> <asp:Parameter Name="CategoryID" Type="Int32" /> <asp:Parameter Name="QuantityPerUnit" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="UnitsInStock" Type="Int16" /> <asp:Parameter Name="UnitsOnOrder" Type="Int16" /> <asp:Parameter Name="ReorderLevel" Type="Int16" /> <asp:Parameter Name="Discontinued" Type="Boolean" /> <asp:Parameter Name="ProductID" Type="Int32" /> </UpdateParameters> <SelectParameters> <asp:ControlParameter ControlID="GridView1" Name="ProductID" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="SupplierID" Type="Int32" /> <asp:Parameter Name="CategoryID" Type="Int32" /> <asp:Parameter Name="QuantityPerUnit" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="UnitsInStock" Type="Int16" /> <asp:Parameter Name="UnitsOnOrder" Type="Int16" /> <asp:Parameter Name="ReorderLevel" Type="Int16" /> <asp:Parameter Name="Discontinued" Type="Boolean" /> </InsertParameters> </asp:SqlDataSource> <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" GridLines="None"> <Fields> <asp:BoundField DataField="ProductName" HeaderText="Name" SortExpression="ProductName" /> <asp:TemplateField HeaderText="Supplier"> <ItemTemplate> <%#Eval("CompanyName") %> </ItemTemplate> <EditItemTemplate> <asp:SqlDataSource ID="Sds1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectString %>" SelectCommand="SELECT SupplierID, CompanyName FROM Suppliers ORDER BY CompanyName" /> <asp:DropDownList ID="SupplierID" runat="server" DataSourceId="Sds1" DataValueField="SupplierID" DataTextField="CompanyName" SelectedValue='<%#Bind("SupplierID")%>' /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Category" > <ItemTemplate> <%#Eval("CategoryName") %> </ItemTemplate> <EditItemTemplate> <asp:SqlDataSource ID="Sds2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectString %>" SelectCommand="SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryName" /> <asp:DropDownList ID="CategoryID" runat="server" DataSourceID="Sds2" DataValueField="CategoryID" DataTextField="CategoryName" SelectedValue='<%#Bind("CategoryID")%>' /> </EditItemTemplate> </asp:TemplateField> <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit" SortExpression="QuantityPerUnit" /> <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" SortExpression="UnitPrice" /> <asp:BoundField DataField="UnitsInStock" HeaderText="Units In Stock" SortExpression="UnitsInStock" /> <asp:BoundField DataField="UnitsOnOrder" HeaderText="Units On Order" SortExpression="UnitsOnOrder" /> <asp:BoundField DataField="ReorderLevel" HeaderText="Reorder Level" SortExpression="ReorderLevel" /> <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" /> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" /> </Fields> <HeaderStyle BackColor="Green" /> <FieldHeaderStyle BackColor="LightGray" Height="20px" Width="110px"/> </asp:DetailsView>
Comments [0] | | # 
Tuesday, December 11, 2007 1:58:53 AM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )

This is the simplest example of how to edit and update a Gridview

Product Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Find Products" />

<br /><br />

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectString %>"
SelectCommand="SELECT * FROM [Products] WHERE ([ProductName] LIKE '%' + @ProductName + '%')"
DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @ProductID"
InsertCommand="INSERT INTO [Products] ([ProductName], [UnitPrice]) VALUES (@ProductName, @UnitPrice)"
UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="ProductName" PropertyName="Text"
Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="Decimal" />
<asp:Parameter Name="ProductID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ProductName" Type="String" />
<asp:Parameter Name="UnitPrice" Type="Decimal" />
</InsertParameters>
</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server"
AllowPaging="true" PageSize="5" AutoGenerateColumns="true"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
</asp:GridView>

Comments [0] | | # 
# Tuesday, November 13, 2007
Tuesday, November 13, 2007 1:41:08 AM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )
Client Confirmation to a GridView Delete
Comments [0] | | #