Navigation

Search

Categories

On this page

and tags in Gridview
Filtering the results in a GridView using jQuery
Filtering a GridView Using jQuery
Export ASP.Net DataGrid DataSet To CSV File
Using a Stored Procedure With a SQLDataAdapter
Nested Gridview
Adding a column in a Gridview using jQuery
How to Get DataKey value of a Row in RowDataBound or RowCommand Event in ASP.Net GridView control
Conditionally Formatting GridView Row based on a Column value in ASP.Net
Change Cell Color Based on Value in Gridview
Total Column for Gridview
Manually Sorting a Gridview
Header AutoFilter Feature in ASP.Net GridView Control
Working with Gridview Control Events
Exporting Data From a Gridview to Excel
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: 378
This Year: 6
This Month: 1
This Week: 0
Comments: 17

Sign In
Pick a theme:

# Thursday, June 23, 2011
Thursday, June 23, 2011 9:15:56 PM (GMT Daylight Time, UTC+01:00) ( Gridview | Javascript/AJAX | jQuery )

Cool example of how to filter the results in a GridView using jQuery using the jQuery QuickSearch Plugin

http://www.msjoe.com/2011/06/filtering-an-asp-net-gridview-control-with-jquery/

Comments [0] | | # 
# Wednesday, June 22, 2011
# Wednesday, June 01, 2011
Wednesday, June 01, 2011 8:58:28 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Export Data | Gridview )

In this article we will present a very useful utility function that can be used to export a data table to a comma separated values (CSV) file. The code first loops through the columns of the data table to export the names of all the data columns. And then in next loop the code iterates over each data row to export all the values in the table. The code represents an event handler that is present on the ASPX page. When user clicks on the button, the data gets exported to GridData.txt file. Once the data is exported is file, you can stream it to the use's browser.

private void OnExportGridToCSV(object sender, System.EventArgs e)

{

        // Create the CSV file to which grid data will be exported.

        StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.txt"), false);

        // First we will write the headers.

        DataTable dt = m_dsProducts.Tables[0];

        int iColCount = dt.Columns.Count;

        for(int i = 0; i < iColCount; i++)

        {

               sw.Write(dt.Columns[i]);

               if (i < iColCount - 1)

               {

                       sw.Write(",");

               }

        }

        sw.Write(sw.NewLine);

        // Now write all the rows.

        foreach (DataRow dr in dt.Rows)

        {

               for (int i = 0; i < iColCount; i++)

               {

                       if (!Convert.IsDBNull(dr[i]))

                       {

                               sw.Write(dr[i].ToString());

                       }

                       if ( i < iColCount - 1)

                       {

                               sw.Write(",");

                       }

               }

               sw.Write(sw.NewLine);

        }

        sw.Close();

}

Comments [0] | | # 
Wednesday, June 01, 2011 8:44:36 PM (GMT Daylight Time, UTC+01:00) ( Export Data | Gridview )

I frequently export data from a Gridview into a CSV file using this CSV writer from http://www.csvreader.com/code/vb/download_datatable.php but I didn’t know how to use a stored procedure in conjunction with a SQLDataAdapter and DataTable.  Here’s how to do it:

Private Sub ExcelExport(ByVal sender As System.Object, ByVal e As System.EventArgs)

       

        Dim MyConnection As SqlConnection

        MyConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("TASSupport_ConnectionString").ConnectionString)

        Dim cmd As New SqlCommand("p_Projects_All", MyConnection)

        With cmd

            .CommandType = CommandType.StoredProcedure

            .Parameters.Add("@pdata", SqlDbType.VarChar, 100)

            .Parameters("@pdata").Value = "Whatever"

        End With

        Dim da As New SqlDataAdapter(cmd)

        Dim myDataTable As DataTable = New DataTable()

        da.Fill(myDataTable)

               

        Try

            MyConnection.Open()

            Response.Clear()

            Response.ClearHeaders()

            Dim writer As New CsvWriter(Response.OutputStream, ","c, Encoding.Default)

            writer.WriteAll(myDataTable, True)

            writer.Close()

                    

            Dim FileDate As String = Replace(FormatDateTime(Now(), DateFormat.ShortDate), "/", "")

            Response.AddHeader("Content-Disposition", "attachment;filename=Enhancement_Requests_" & FileDate & ".csv")

            Response.ContentType = "application/vnd.ms-excel"

            Response.End()

        Finally

            If MyConnection.State <> ConnectionState.Closed Then MyConnection.Close()

            MyConnection.Dispose()

            MyConnection = Nothing

            myDataTable.Dispose()

            myDataTable = Nothing

        End Try

    End Sub

Comments [0] | | # 
# Wednesday, May 18, 2011
Wednesday, May 18, 2011 5:21:32 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Gridview )

A great example of how to nest one gridview inside of another and collapse/expand the set of nested records.

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim gv As GridView = e.Row.FindControl("GridView2")

            Dim dbSrc As New SqlDataSource

            dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings("TASSupport_ConnectionString").ConnectionString

            dbSrc.SelectCommand = "SELECT ResponseID, Response, TicketID, Response_Date, Responder FROM v_Responses WHERE TicketID = '" & _

                e.Row.DataItem("TicketID").ToString & "' ORDER BY Response_Date DESC"

            gv.DataSource = dbSrc

            gv.DataBind()

        End If

End Sub

<div id="dvGrid" class="grid">

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="datatable"

        BorderWidth="1px" DataKeyNames="TicketID" BackColor="White"

        GridLines="Horizontal" DataSourceID="dsAllTickets"

        CellPadding="3" BorderColor="#E7E7FF" Width="95%" HorizontalAlign="Center"

        AllowSorting="True" BorderStyle="None" AllowPaging="True"

        PageSize="25" EnableModelValidation="True" OnRowDataBound="GridView1_RowDataBound">

        <EmptyDataTemplate>

            <asp:Label ID ="lblEmptyDataTemplate" runat ="server" Text ="No tickets have been assigned to you" CssClass="nomatch" />

        </EmptyDataTemplate>

        <Columns>

           

            <asp:TemplateField HeaderText=" ">

                <ItemTemplate>

                    <a href="javascript:switchViews('div<%# Eval("TicketID") %>', 'one');">

                        <img id="imgdiv<%# Eval("TicketID") %>" alt="Click to show/hide responses" border="0"

                            src="../images/expand_button.png" />

                    </a>

                </ItemTemplate>

                <AlternatingItemTemplate>

                    <a href="javascript:switchViews('div<%# Eval("TicketID") %>', 'alt');">

                        <img id="imgdiv<%# Eval("TicketID") %>" alt="Click to show/hide responses" border="0"

                            src="../images/expand_button.png" />

                    </a>

                </AlternatingItemTemplate>

            </asp:TemplateField>

            <asp:TemplateField HeaderText="Ticket ID" SortExpression="TicketID" ItemStyle-CssClass="first"

                HeaderStyle-CssClass="first">

                <ItemTemplate>

                    <a href="ticket.detail.aspx?TicketID=<%#Eval("TicketID") %>"><%#Eval("TicketID")%></a>

                </ItemTemplate>

            </asp:TemplateField>

            <asp:BoundField DataField="Date_Received" HeaderText="Date" SortExpression="Date_Received" />

            <asp:BoundField DataField="Request_Type" HeaderText="Request Type" SortExpression="Request_Type" />

               <asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />

            <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />

            <asp:BoundField DataField="Urgency" HeaderText="Urgency" SortExpression="Urgency" />

            <asp:BoundField DataField="Requestor_Name" HeaderText="Requestor Name" SortExpression="Requestor_Name" />

            <asp:BoundField DataField="TAS_Name" HeaderText="Assigned To" SortExpression="TAS_Name" />           

             <asp:TemplateField HeaderText=" ">

                        <ItemTemplate>

                            </td></tr>

                            <tr>

                                <td colspan="100%">

                                    <div id="div<%# Eval("TicketID") %>" style="display:none;position:relative;left:25px;" >

                                        <asp:GridView ID="GridView2" runat="server" Width="80%"

                                            AutoGenerateColumns="false" DataKeyNames="ResponseID"

                                            EmptyDataText="No responses for this ticket.">

                                            <RowStyle CssClass="row" />

                                            <AlternatingRowStyle CssClass="rowalternate" />

                                            <HeaderStyle CssClass="gridcolumnheader" />

                                            <Columns>

                                                <asp:BoundField DataField="Response" HeaderText="Response" />

                                                <asp:BoundField DataField="Response_Date" HeaderText="Date" />

                                                <asp:BoundField DataField="Responder" HeaderText="Responder" />

                                            </Columns>

                                        </asp:GridView>

                                    </div>

                                </td>

                            </tr>

                        </ItemTemplate>

                    </asp:TemplateField>

        </Columns>

        <RowStyle CssClass="row" />

        <AlternatingRowStyle CssClass="rowalternate" />

        <FooterStyle CssClass="gridcolumnheader" />

        <PagerStyle HorizontalAlign="Left" CssClass="gridpager" />

        <HeaderStyle CssClass="gridcolumnheader" />

      </asp:GridView>

    </div>

<script language="javascript" type="text/javascript">

    function switchViews(obj,row)

    {

        var div = document.getElementById(obj);

        var img = document.getElementById('img' + obj);

        

        if (div.style.display=="none")

            {

                div.style.display = "inline";

                if (row=='alt')

                    {

                        img.src = "../images/expand_button_down.png"; mce_src = "../images/expand_button_down.png";

                    }

                else

                    {

                        img.src = "../images/expand_button_down.png"; mce_src = "../images/expand_button_down.png";

                    }

                img.alt = "Close to view other customers";

            }

        else

            {

                div.style.display = "none";

                if (row=='alt')

                    {

                        img.src = "../images/expand_button.png"; mce_src = "../images/expand_button.png";

                    }

                else

                    {

                        img.src = "../images/expand_button.png"; mce_src = "../images/expand_button.png";

                    }

                img.alt = "Expand to show orders";

            }

    }

   

</script>

<asp:SqlDataSource ID="dsAllTickets" runat="server" SelectCommand="p_AllTickets" SelectCommandType="StoredProcedure"

     ConnectionString="<%$ ConnectionStrings:TASSupport_ConnectionString %>"  OnSelected="OnSelectedHandler">

p

Comments [0] | | # 
# Tuesday, March 15, 2011
Tuesday, March 15, 2011 8:15:32 PM (GMT Standard Time, UTC+00:00) ( Gridview | Javascript/AJAX | jQuery )
<script type="text/javascript">
$(function () {
var checked = $('input:checkbox').click(function (e) {
calculateSum(4); //Sum of 4th column
});

 
function calculateSum(colidx) {
total = 0.0;
$("tr:has(:checkbox:checked) td:nth-child(" + colidx + ")").each(function() {
total += parseFloat($(this).text());
});
$('#tot').text("Your total amount is: " + total.toFixed(2));
}
});
</script>

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="EmployeeId" SortExpression="Id" />
<asp:BoundField DataField="AddOnType" HeaderText="AddOn Type" SortExpression="AddOnType" />
<asp:BoundField DataField="AddOnCost" HeaderText="AddOn Cost" SortExpression="AddOnCost" />
</Columns>

</asp:GridView>

Comments [0] | | # 
# Friday, February 18, 2011
Friday, February 18, 2011 1:23:40 PM (GMT Standard Time, UTC+00:00) ( Gridview )

This little code snippet will help us to find the data keys associated with a row in DataBound and RowCommand event in codebehind file.

 

ASPX
 
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
            DataKeyNames="UserID" OnRowDataBound="gvUsers_RowDataBound"
            RowStyle-CssClass="Row" onrowcommand="gvUsers_RowCommand">
                    <Columns>                      
                        <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />     
                         <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" /> 
                         <asp:TemplateField>
                         <ItemTemplate>
                        <asp:Button runat="server" Text="SELECT" CommandName="Select" />                             
                        </ItemTemplate>
                         </asp:TemplateField>                       
                    </Columns>                   
                    <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />
     </asp:GridView>

 

RowDataBound Event
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            object objTemp = gvUsers.DataKeys[e.Row.RowIndex].Value as object;
            if (objTemp != null)
            {
               string id = objTemp.ToString();
//Do your operations
            }

                   }
    }

 

RowCommand Event
   
protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      Control ctl = e.CommandSource as Control;
      GridViewRow CurrentRow = ctl.NamingContainer as GridViewRow;
      object objTemp = gvUsers.DataKeys[CurrentRow.RowIndex].Value as object;
      if (objTemp != null)
      {
          string id = objTemp.ToString();
//Do your operations
      }
    }

Comments [0] | | # 
# Wednesday, February 16, 2011
Wednesday, February 16, 2011 5:34:35 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )

Sometimes, we will require highlighting GridView control's row based on a value in particular column. For example, highlighting only admin users in a users list or highlighting all permanent employees from employees list that has both permanent and contract employees in Employee table.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUsers();
        }
    }
    public void BindUsers()
    {
        DataTable dt = GetUsersForModeration();       
        gvUsers.DataSource = dt;
        gvUsers.DataBind();
    }
    public DataTable GetUsersForModeration()
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand("SP_GetUsersForModeration", con);
        com.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter ada = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        ada.Fill(ds);
        return ds.Tables[0];
    }
    protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[3].Text == "Admin")
            {
                e.Row.BackColor = System.Drawing.Color.Orange;
                e.Row.ForeColor = System.Drawing.Color.White;
            }
        }
    }

The above code will make all admin user's row background color to orange and foreground color to white.


Note

The above code "e.Row.Cells[3].Text" in RowDataBound event will not work if the column text we are fetching is template column. In this case, use DataBinder.Eval(e.Row.DataItem,"Role") to fetch the text. Hence, the above code will become:


protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (DataBinder.Eval(e.Row.DataItem,"Role")== "Admin")
            {
                e.Row.BackColor = System.Drawing.Color.Orange;
                e.Row.ForeColor = System.Drawing.Color.White;
            }
        }
    }

Comments [0] | | # 
Wednesday, February 16, 2011 1:15:43 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | Gridview )
 
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) 
  If e.Row.RowType = DataControlRowType.DataRow Then
    ' Get value of third column. Index is zero based, to 
    ' get text of third column we use Cells[2].Text
    Dim CellValue As Integer = Convert.ToInt32(e.Row.Cells(2).Text) 
    ' If value is greater of 10, change format
    If CellValue > 10 Then
      ' Use this syntax to change format of complete row
      e.Row.BackColor = System.Drawing.Color.Yellow
      ' Use this syntax to change format of single cell
      e.Row.Cells(2).BackColor = System.Drawing.Color.Red
    End If
  End If
End Sub
Comments [0] | | # 
# Thursday, February 10, 2011
Thursday, February 10, 2011 1:45:14 PM (GMT Standard Time, UTC+00:00) ( Gridview )

<asp:TemplateField HeaderText="Amount" FooterStyle-Font-Bold="True">

<ItemTemplate>

    <%# GetUnitPrice(Decimal.Parse(Eval("Amt").ToString())).ToString("C2")%>

</ItemTemplate>

<FooterTemplate>

    <%# GetTotal().ToString("C2")%>

</FooterTemplate>

</asp:TemplateField>

 

Enable footer in Gridview  ShowFooter="true"

 

    Dim TotalUnitPrice As Decimal = 0.0

    Function GetUnitPrice(ByVal Price As Decimal) As Decimal

        TotalUnitPrice += Price

        Return Price

    End Function

   

    Function GetTotal() As Decimal

        Return TotalUnitPrice

    End Function

Comments [0] | | # 
# Tuesday, December 14, 2010
Tuesday, December 14, 2010 6:57:45 PM (GMT Standard Time, UTC+00:00) ( Gridview )
When not using a SqlDataSource and you want to sort the columns, you need to take some extra steps?

  Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
Dim strSortString = Convert.ToString(e.SortExpression) & " " & GetSortDirection(e.SortDirection)
lblSortExpression.Text = strSortString.ToString

 
'Now bind the gridview with the results

BindGridView()

End Sub

  
Private Function GetSortDirection(ByVal column As String) As String
' By default, set the sort direction to ascending.
Dim sortDirection = "ASC"
' Retrieve the last column that was sorted.
Dim sortExpression = TryCast(ViewState("SortExpression"), String)
If sortExpression IsNot Nothing Then
' Check if the same column is being sorted.
' Otherwise, the default value can be returned.
If sortExpression = column Then
Dim lastDirection = TryCast(ViewState("SortDirection"), String)
If lastDirection IsNot Nothing _
AndAlso lastDirection = "ASC" Then
sortDirection = "DESC"
End If
End If
End If
' Save new values in ViewState.
ViewState("SortDirection") = sortDirection
ViewState("SortExpression") = column
Return sortDirection
End Function

  Sub BindGridView()

Dim SqlConn As SqlConnection
Dim SqlCmd As SqlCommand
Dim ds As DataSet
Dim strSQL As String
SqlConn = New SqlConnection(ConfigurationManager.ConnectionStrings("VandV_ConnectionString").ConnectionString)
strSQL = "p_Summary"
SqlCmd = New SqlCommand(strSQL, SqlConn)
SqlCmd.CommandType = Data.CommandType.StoredProcedure
SqlCmd.Parameters.AddWithValue("@OrgCode", lblOrgCode.Text.ToString())
SqlCmd.Parameters.AddWithValue("@ObligationStatus", intObligationStatus)
Try
SqlCmd.Connection.Open()
Dim MyAdapter As New SqlDataAdapter(SqlCmd)
ds = New DataSet()
MyAdapter.Fill(ds, "SearchResults")
lblRecordCount.Text = "Showing " & ds.Tables(0).Rows.Count() & " records."

ds.Tables(0).DefaultView.Sort = lblSortExpression.Text
GridView1.DataSource = ds.Tables("SearchResults").DefaultView
GridView1.DataBind()
Finally

SqlConn.Close()
End Try
End Sub

  <asp:GridView...
OnSorting="GridView1_Sorting" />

Comments [0] | | # 
# Tuesday, December 07, 2010
Tuesday, December 07, 2010 2:24:06 PM (GMT Standard Time, UTC+00:00) ( Gridview )
Great article on how to add a cropdownlist in the header of a Gridview control which filters the records.

  http://archive.aspsnippets.com/post/2009/11/26/Excel-like-AutoFilter-Feature-in-ASPNet-GridView-Control.aspx

Comments [0] | | # 
# Monday, December 06, 2010
Monday, December 06, 2010 5:23:54 PM (GMT Standard Time, UTC+00:00) ( Gridview )
The Gridview supports the following set of events raised when the control displays its rows:

 

  • DataBinding: Raised immediately before the Gridview is bound to its data source. Protected Sub GridView1_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
    End Sub
  • DataBound: Raised immediately after Gridview is bound to its data source.
    Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
    End Sub
  • RowCreated: Raised when each row in Gridview is created.
    Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    End Sub
  • RowDataBound: Raised when each row in Gridview is bound to data.
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    End Sub
  
The Gridview control includes the following set of events raised when you edit records:

 

  • RowCommand: Raised when an event is raised by a control  contained in Gridview.
    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
    End Sub
  • RowUpdating:  Raised immediately before Gridview updates a record.
    Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
    End Sub
  • RowUpdated: Raised immediately after Gridview updates a record.
    Protected Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs)
    End Sub
  • RowDeleting: Raised immediately before Gridview deletes a record.
    Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs)
    End Sub
  • RowDeleted: Raised immediately after Gridview deletes a record.
    Protected Sub GridView1_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs)
    End Sub
  • RowCancelingEdit: Raised when you cancel updating a record.
    Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)
    End Sub

  Finally, the Gridview control supports the following events related to sorting, selecting and paging: 

  • PageIndexChanging: Raised immediately before the current page changes.
    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
    End Sub
  • PageIndexChanged: Raised immediately after the current page changes.
    Protected Sub GridView1_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    End Sub 
  • Sorting: Raised immediately before sorting.
    Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
    End Sub
  • Sorted: Raised immediately after sorting.
    Protected Sub GridView1_Sorted(ByVal sender As Object, ByVal e As System.EventArgs)
    End Sub
  • SelectedIndexChanging: Raised immediately before a row is selected.
    Protected Sub GridView1_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs)
    End Sub
  • SelectedIndexChanged: Raised immediately after a row is selected.
    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    End Sub
Comments [0] | | # 
# Thursday, November 11, 2010
Thursday, November 11, 2010 2:05:34 AM (GMT Standard Time, UTC+00:00) ( Gridview )

Here’s another example of this.  Here’s a previous example.

Sub doExcel(ByVal Source As Object, ByVal E As EventArgs)
        If gvCompanyProfileViews.Rows.Count.ToString + 1 < 65536 Then
            gvCompanyProfileViews.AllowPaging = "False"
            gvCompanyProfileViews.AllowSorting = "False"
            gvCompanyProfileViews.DataBind()
            gvCompanyProfileViews.RowStyle.BackColor = Drawing.Color.White
            gvCompanyProfileViews.HeaderStyle.BackColor = Drawing.Color.White
            gvCompanyProfileViews.BorderStyle = BorderStyle.None
            Dim tw As New StringWriter()
            Dim hw As New System.Web.UI.HtmlTextWriter(tw)
            Dim frm As HtmlForm = New HtmlForm()
            Dim dteTodaysDate As String
            dteTodaysDate = System.DateTime.Now.ToShortDateString()
            Response.ContentType = "application/vnd.ms-excel"
            Response.AddHeader("content-disposition", "attachment;filename=Academic_Logins_" & dteTodaysDate & ".xls")
            Response.Charset = ""
            EnableViewState = False
            Controls.Add(frm)
            frm.Controls.Add(gvCompanyProfileViews)
            frm.RenderControl(hw)
            Response.Write(tw.ToString())
            Response.End()
            gvCompanyProfileViews.AllowPaging = "True"
            gvCompanyProfileViews.DataBind()
        Else
            lblError.Text = "Too many rows - Export to Excel not possible"
        End If
    End Sub
Comments [0] | | # 
# 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] | | #