How to get GridView row index without triggering this exception? - asp.net

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

Related

How to dynamically assign ID to a checkbox in a for-each cycle

I have the following code in a ascx : I run a SQL query and I put it in a Datatable. Then I show the values in the page like this
<% For each row As DataRow In myDataTable.Rows %>
<%=row("something") %>
<%=row("somethingelse") %>
<asp:CheckBox ID="CheckBox1" runat="server" />
<% next %>
Now... how can I set the ID of the checkbox dynamically?
something like
<asp:CheckBox ID="<%=row("MyId")%>" runat="server" />
that obviously do not work.
I need to set the id as the value I get from the DB so if it is checked I can pass the checked id to another page.
The problem is that row("MyId") returns type of object so you need to convert it to string to be able to bind it to Checkbox
<asp:CheckBox ID="<%=row('MyId').ToString()%>" runat="server" />
See: DataRow.Item[] Property
Hum, would not a data control say like listview, or gridview be better here?
You can have this markup:
<asp:GridView ID="GVHotels" runat="server" class="table" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="ckActive" runat="server"
Checked=<%# Eval("Active") %> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now to load we have this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim strSQL As String =
"SELECT TOP 10 FirstName, LastName, HotelName, City, Description, Active
FROM tblHotels WHERE description is not null ORDER BY HotelName"
GVHotels.DataSource = MyRst(strSQL)
GVHotels.DataBind()
End If
End Sub
and we get this:
So, it is a lot less work to do the above.
Even if you don't have a bound check box, you can even feed the grid the data, and display a un-bound check box for selecting rows if that what you need/want.

Gridview button onclick not firing from a Microsoft Developer Network Example

I created a simple Grid view with Multiple columns and add a button so when clicked pass the values of the row to a different webform but button on click not firing. I use the example code from the link
: http://msdn.microsoft.com/en-us/library/bb907626(v=vs.100).aspx
And this is my code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False">
<Columns>
<%--<asp:HyperLinkField HeaderText="Edit" NavigateUrl="FormReport2.aspx"
Text="Edit" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="fldEmployeeID" HeaderText="EmployeeID"
SortExpression="fldEmployeeID" />
<asp:BoundField DataField="fldAbsentDate" HeaderText="AbsentDate"
SortExpression="fldAbsentDate" />
<asp:BoundField DataField="fldAbsentCode" HeaderText="AbsentCode"
SortExpression="fldAbsentCode" />
<asp:BoundField DataField="fldRuleViolationWarningType"
HeaderText="Rule Violation Warning Type"
SortExpression="fldRuleViolationWarningType" />
<asp:BoundField DataField="fldRuleViolationIssueDate"
HeaderText="Rule Violation Issue Date"
SortExpression="fldRuleViolationIssueDate" />
<asp:BoundField DataField="fldLOAEndDate" HeaderText="LOA End Date"
SortExpression="fldLOAEndDate" />
</Columns>
</asp:GridView>
code behind
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
Any help would be very appreciated. And also what would be the best way to pass the values from the row to a different web form from the code behind?
You forgot to sing up for the event. See the last line here:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False"
OnRowCommand="GridView1_RowCommand">

Working with ASP.Net GridView sorting and paging

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

Custom Save button in asp.net

my question is simple, how do i create a custom save and update button for records entered in a detail view. I dont want to use the ones given. thanks a lot.
You have a couple of options. One is the OnItemCommand and you'll roll your own commands.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.itemcommand.aspx
The easier way is to use the OnItemInserted and OnItemUpdating events. Just send the Insert or Update commands instead as appropriate and you can use easier EventArgs
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.iteminserting.aspx
<http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.itemupdating.aspx
From these pages, basically what you'll do is capture a command from a button in your DetailsView.
Custom "Add" commamnd with ItemCommand
Sub CustomerDetailView_ItemCommand(ByVal sender As Object, ByVal e As DetailsViewCommandEventArgs)
' Use the CommandName property to determine which button
' was clicked.
If e.CommandName = "Add" Then
' Do your work here if Add Contact is clicked
End If
End Sub
Easier built in Insert command with ItemInserting
Sub CustomerDetailView_ItemInserting((ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs)
' Access the actual rows with
Some variable1 = e.Values("CustomerID")
Some variable2 = e.Values("CompanyName")
Some variable3 = e.Values("City")
' Do something with them
End Sub
Code front
<asp:DetailsView ID="CustomerDetailView"
DataSourceID="DetailsViewSource"
AutoGenerateRows="false"
DataKeyNames="CustomerID"
AllowPaging="true"
OnItemCommand="CustomerDetailView_ItemCommand"
OnItemInserting="CustomerDetailView_ItemInserting"
OnItemUpdating="CustomerDetailView_ItemUpdating"
runat="server">
<FieldHeaderStyle BackColor="Navy" ForeColor="White" />
<Fields>
<asp:BoundField DataField="CustomerID" HeaderText="Store ID" />
<asp:BoundField DataField="CompanyName" HeaderText="Store Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Name">
<InsertItemTemplate>
<asp:Button ID="btAddContact" runat="server" Text="Add Contact" CommandName="Add" />
Or
<asp:Button ID="btAddContact" runat="server" Text="Add Contact" CommandName="Insert" />
</InsertItemTemplate>
<EditItemTemplate>
<asp:Button ID="btAddContact" runat="server" Text="Save Contact" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
You can use any button that implements the IButtonControl interface. The key is to set the CommandName correctly. Hopefully this will give you the freedom to style your button the way you need to.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.commandname.aspx
You can find a list of the relevant command names here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemcommand.aspx
<asp:ImageButton runat="server" ... CommandName="Save" />
<asp:LinkButton runat="server" ... CommandName="Update" />

Grid Checkbox value not changed, how to get value on button click?

i am using asp.net for my web application when i click on checkbox inside gridview and after that i check its value on button click it does not show me the exact value
here is asp code
<asp:GridView ID="dgvMenu" runat="server" Width="100%" CssClass="grid" GridLines="None"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
View
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="View" runat="server" Checked="<%#Bind('View') %>" />
</ItemTemplate>
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="Menu" HeaderText="Menu Name">
<HeaderStyle HorizontalAlign="Left" CssClass="firstcol" />
<ItemStyle CssClass="firstcol" />
</asp:BoundField>
</Columns>
</asp:GridView>
and here is its vb version to get its value on button click version
For Each item As GridViewRow In dgvMenu.Rows
Dim MenuName As String = item.Cells.Item(1).Text
Dim chkView As CheckBox = DirectCast(item.FindControl("View"), CheckBox)
Next
i want to check its value whether its checked or unchecked so that i can process its value
I assume that your binding your GridView even on postbacks. You should only bind it if not PageIsPostback.
Put this into Page_Load:
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' following function loads data and binds it to the GridView '
BindGrid()
End If
End Sub
If you DataBind the Grid on every postback, ViewState cannot be reloaded, hence all changed values are lost and events will not be triggered correctly.

Resources