Working with ASP.Net GridView sorting and paging - asp.net

We set up an ASP.Net GridView and included sorting and paging. When the user clicks on the GridView column header links for sorting the data or if the user clicks on the numbers links at the bottom of the GridView for paging the data, nothing happens.
Here is a cut down version of the markup for the GridView:
<asp:UpdatePanel
ID="UpdatePanelSummary"
runat="server"
UpdateMode="Always">
<ContentTemplate>
<h1>Maintenance</h1>
<% '-- GridView (Grid) for summary. -- %>
<% '-- The user chooses a summary row from here and details are shown in a DetailsView. -- %>
<% '--------------------------------------------------------------------------------------- %>
<asp:GridView
ID="GridViewSummary"
runat="server"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="ID"
Width="224px"
AllowPaging="True"
PageSize="7">
<Columns>
<asp:BoundField DataField="Unit" HeaderText="Unit"
SortExpression="Unit" />
<asp:BoundField DataField="TheName" HeaderText="Name"
SortExpression="TheName" />
<asp:BoundField DataField="ID"
HeaderText="ID" SortExpression="ID" InsertVisible="False" ReadOnly="True"
Visible="False" />
<asp:CommandField ButtonType="Button" SelectText="Select Unit Details"
ShowSelectButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Since nothing is happening, we are assuming we need to write some coding in the code-behind file. Can you show us what coding is needed to wake up the sorting and paging?

Check out this post
sorting and paging with gridview asp.net
Basically you need to add server side event handlers for sorting and paging.
Here is an example - you can copy/paste most of it.
http://www.dotnetspider.com/resources/1249-Grid-View-Paging-Sorting.aspx

Related

How to get GridView row index without triggering this exception?

I am trying to obtain the row index on a button click in an asp gridview.
<asp:Panel runat="server" Visible="true" ID="pnlGV">
<asp:GridView ID="gvTasks" runat="server" CssClass="table table-hover table-striped" DataKeyNames="TaskID" AutoGenerateColumns="False" AllowPaging="true" AllowSorting="true" PageSize="10" SkinID="standard_gv" EmptyDataText="No tasks match your search terms">
<Columns>
<asp:BoundField SortExpression="TaskID" DataField="TaskID" ReadOnly="true" HeaderText="Task ID" />
<asp:BoundField SortExpression="ProjectCode" DataField="ProjectCode" ReadOnly="true" HeaderText="Project Code" />
<asp:BoundField SortExpression="TaskType" DataField="TaskType" ReadOnly="true" HeaderText="Task Type" />
<asp:BoundField SortExpression="TaskDescription" DataField="TaskDescription" ReadOnly="true" HeaderText="Description" />
<asp:BoundField SortExpression="BizArea" DataField="BizArea" ReadOnly="true" HeaderText="Business Area" />
<asp:BoundField SortExpression="TargetDate" DataField="TargetDate" ReadOnly="true" HeaderText="Target" />
<asp:BoundField SortExpression="TaskStatus" DataField="TaskStatus" ReadOnly="true" HeaderText="Status" />
<asp:BoundField SortExpression="TaskPriority" DataField="TaskPriority" ReadOnly="true" HeaderText="Priority" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnNotes" runat="server" CommandName="notes" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" Text="Notes" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
and
Protected Sub gvTasks_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
Try
If (e.CommandName = "notes") Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = gvTasks.Rows(index)
notesAcc.Populate(CInt(gvTasks.Rows(index).Cells(0).Text))
notesAcc.Visible = True
End If
Catch ex As Exception
Throw
End Try
End Sub
This just throws this error message at me:
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
and I have no idea how to fix it.
Would anyone be able to give me some insight?
Thank you in advance.
Tom
Edit:
Thank you for the responses, it is much appreciated.
What is notesAcc.Populate(CInt(gvTasks.Rows(index).Cells(0).Text)) dong? If you comment it out does the problem go away?
That is calling a Sub from an .ascx file, and I wouldn't imagine so as I've breakpointed the event handler and it doesn't even reach it.
Do you get that error when page loads or when you click the button?
When I click the button.
It is probably worth mentioning that I am no longer getting the error. I made a tiny insignificant change - so small I can't even remember what it was - and it's gone away, however, it's still not working as intended. The event handler doesn't trigger and I have no idea why. Again, would anyone be able to give me a nudge in the right direction?
You can do one of 3 things:
Set AutoEventWireUp to true.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Manager.Default" %>
or
Add the event to the GridView
<asp:GridView ID="gvTasks" runat="server" CssClass="table table-hover table-striped" DataKeyNames="TaskID" AutoGenerateColumns="False" AllowPaging="true" AllowSorting="true" PageSize="10" SkinID="standard_gv" EmptyDataText="No tasks match your search terms" OnRowCommand="gvTasks_RowCommand">
or
Add the handles keyword to the method
Protected Sub gvTasks_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvTasks.RowCommand
I hope it helps

C# How do I create a Hyperlink OnClick event on GridView?

I'm having trouble creating the GridView I want.
I would like the user to get inside the website and see the GridView which is attached to a DB.
Columns are: ID, InsertionTime, Filepath, ProccessedByUser
Now I want the user to click the filepath he/she would like to process. When he/she clicks the filepath, I want their username (logged in with built-in asp website authentication) to be updated (added) into DB.
My markup is standard and I haven't got to manage with code behind.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:HyperLinkField DataNavigateUrlFields="path" DataTextField="path"
HeaderText="path" />
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
I tried using HyperlinkField but it doesn't seem to support onlick events.
Any suggestions?
Thanks.
I assume you are looking for the LinkButton control which has an OnClick event.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:TemplateField HeaderText="Path" SortExpression="Filepath">
<ItemTemplate>
<asp:LinkButton ID="LbPath" runat="server"
Text='<%# Eval("Filepath") %>'
CommandName="PathUpdate"
CommandArgument='<%#Bind("path") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
Now you can handle the LinkButton's click event or the GridView's RowCommand event.
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "PathUpdate")
{
string path= e.CommandArgument.ToString();
// do you what you need to do
}
}
Note that i've used a TemplateField which is the most dynamic column type in a GridView since you can add anything you want, even nested GridViews or UserControls.
You could use a ButtonField, and then handle OnRowCommand of the gridview. Example here:
http://msdn.microsoft.com/SV-SE/library/system.web.ui.webcontrols.buttonfieldbase.buttontype.aspx
You can set the ButtonType attribute of ButtonField to display the button as a Link.

Creating Edit Page in ASP.NET

Im a newbie in asp.net and im about to do a edit page for my news and announcement page.
This is my sample code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="news_id" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="news_id" HeaderText="news_id" InsertVisible="False"
ReadOnly="True" SortExpression="news_id" />
<asp:BoundField DataField="news" HeaderText="news" SortExpression="news" />
<asp:BoundField DataField="news_date" HeaderText="news_date"
SortExpression="news_date" />
<asp:BoundField DataField="news_data" HeaderText="news_data"
SortExpression="news_data" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TDBSConnectionString %>"
SelectCommand="SELECT [news_id], [news], [news_date], [news_data] FROM [ibsi.news]">
</asp:SqlDataSource>
I put the data into a gridview to show all the data from the database.
how can i use this dataview to edit my content or can what can i use in the toolbar to create one edit module.
The link http://msdn.microsoft.com/en-us/library/ms972948.aspx might be able to help you out.
The ASP.NET GridView allows for a row of data to be edited by setting the EditIndex property of the GridView, placing the entire row in edit mode....
To implement this,go throught following article of codeproject:
http://www.codeproject.com/Articles/18136/Edit-Individual-GridView-Cells-in-ASP-NET

I cannot make the headers of my gridview click able for sorting

I have a gridview that I populate based on a query to a db. I'm trying to add sorting on my gridview but I cannot make my column headers clickable. I have allow sorting set to true, and I have my OnSorting event set. My columns are of a few different types. I know the code I need to have in my code behind, but I cannot click on the headers for some reason. Any help on what I'm missing would be appreciated.
<asp:GridView ID="Grid1" runat="server"
AutoGenerateColumns="False"
OnSelectedIndexChanging="Selected_Row_Changing"
DataKeyNames="ApplicationId"
AllowPaging="True"
OnPageIndexChanging="Grid1_PageIndexChanging"
AllowSorting="True"
OnSorting="Grid1_Sorting"
OnRowCreated="OnRowCreated"
OnRowCommand="Grid1_RowCommand"
OnRowDataBound="Grid1_RowDataBound">
<Columns>
<asp:templatefield ...>
<itemtemplate>
<asp:linkbutton .../>
</itemtemplate>
</asp:templatefield>
<asp:BoundField ... />
<asp:HyperLinkField ... />
<asp:ButtonField ... />
</Columns>
</asp:GridView>
You don't have set the SortExpression, have you?
For example:
<asp:boundfield datafield="CompanyName"
headertext="CompanyName"
headerstyle-wrap="false"
sortexpression="CompanyName"/>
Make sure you're not setting the Header Template but rather set the HeaderText attribute for the TemplateField

Adding a validator to the gridview textbox, created in edit-mode of a bound field

take a look at this sample code: (question bellow)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource2"
AutoGenerateColumns="False" onrowupdated="GridView1_RowUpdated"
DataKeyNames="Product_Id">
<Columns>
<asp:ImageField DataImageUrlField="Image_Name" HeaderText="Image_Name"
ReadOnly="True" >
<ItemStyle Width="50px" Height="50px" Wrap="true"/>
</asp:ImageField>
<asp:BoundField DataField="Product_Id" HeaderText="Product_Id"
InsertVisible="False" ReadOnly="True" SortExpression="Product_Id">
</asp:BoundField>
<asp:BoundField DataField="Product_Name" HeaderText="Product_Name"
SortExpression="Product_Name" />
<asp:BoundField DataField="Category_Name" HeaderText="Category_Name"
SortExpression="Category_Name" ReadOnly="true" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Size" HeaderText="Size"
SortExpression="Size" />
<asp:BoundField DataField="Price" HeaderText="Price"
SortExpression="Price" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
Assume I initialize an SqlDataSource, add a parameter and so on.
The thing is, that when a user clicks edit we get a textbox to edit the colnumn value.
I want to validate the data enter by the user before the update is performed and the new
data is propagated back to the server.How?
10x a lot!
You need to convert the BoundField into a TemplateField. Then you can add a validator to the actual TextBox control.
Option 1:
But from the UNKNOWN answer, the Microsoft recommends the same.. as he told.
ref: http://msdn.microsoft.com/en-us/library/bb426882.aspx#aspnett19_vldcntredtuics_topic2
Option 2:
But, we can do.
You need to add the validation either the javascript validation or server side validation
control, when the GridView's DataBound event is happening at runtime on the particular
TableCell of the Gridview rows.
Hence, when you click the update button that custom generated javascript or the validation
control will check for the validation on editing the values.
This process is more harder than the converting boundfield to templatefield
refer: http://www.aspdotnetcodes.com/GridView_Dynamic_Validation.aspx
Option 3:
And you can go for server side validation on the values instead of client side validation:
refer: http://msdn.microsoft.com/en-us/library/bb332383.aspx

Resources