Issues with Asp.net Gridview Paging - asp.net

I have used the Gridview_PageIndexChanging event in asp.net.i have used the code like this:
gridFileDetails.PageIndex = e.NewPageIndex
During the run time when i clicked the next page,it generates an error:
An exception of type
'System.InvalidCastException' occurred
in FFK.DLL but was not handled in user
code
Additional information: Unable to cast
object of type
'System.Web.UI.WebControls.ContentPlaceHolder'
to type
'System.Web.UI.WebControls.GridViewRow'.
in the RowCommand event,
I have used the following RowCommand event:
Protected Sub gridFileDetails_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridFileDetails.RowCommand
Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
Dim rowkey As DataKey = Me.gridFileDetails.DataKeys(row.DataItemIndex)
Dim key As String = rowkey(0).ToString()
If e.CommandName = "FileStatus" And e.CommandArgument <= 0 Then
Response.Redirect("FFKFile.aspx?FileId=" + key)
ElseIf e.CommandName = "TradexStatus" And e.CommandArgument <= 0 Then
Response.Redirect("TradeX.aspx?FileId=" + key)
ElseIf e.CommandName = "BondStatus" And e.CommandArgument <= 0 Then
Response.Redirect("BondMaster.aspx?FileId=" + key)
ElseIf e.CommandName = "FDStatus" And e.CommandArgument <= 0 Then
Response.Redirect("FrmFileDocument.aspx?FileId=" + key)
ElseIf e.CommandName = "InvoiceStatus" And e.CommandArgument <= 0 Then
Response.Redirect("InvoiceMaster.aspx?FileId=" + key)
ElseIf e.CommandName = "PDStatus" And e.CommandArgument <= 0 Then
Response.Redirect("PackagingDetails.aspx?FileId=" + key)
End If
End Sub
can you resolve this problem?
i am getting the error in the first line in RowCommand event ,ie.,
Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
In the PageIndexChanging event i have written as follows:
Protected Sub gridFileDetails_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gridFileDetails.PageIndexChanging
gridFileDetails.PageIndex = e.NewPageIndex
End Sub

Instead of this:
Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
Use the index from the EventArgs to grab the row programmatically like this:
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = gridFileDetails.Rows(index)

Referencing the MSDN for the System.Web.UI.WebControls.GridViewCommandEventArgs class, the example there for extracting the gridviewrow is this:
' Convert the row index stored in the CommandArgument
' property to an Integer.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button clicked
' by the user from the Rows collection.
Dim row As GridViewRow = ContactsGridView.Rows(index)
See if that helps you get your row without the cast error.

This might help :
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = gridFileDetails.Rows(index)

Related

Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.GridViewRow'

I need your help on this. I am not sure why I am getting this error. Here is what I am trying to do. I am populating a button into the GridView based on the data from database however I have no issue with that. But the issue comes when I am trying to do RowCommand. I am trying to get the individual id from each row so that i can use for my sql query
Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
Dim row As GridViewRow = e.Row
If row.RowType = DataControlRowType.DataRow Then
Dim lb2 As New LinkButton
lb2.ID = "lbCancel"
lb2.Text = "Cancel"
lb2.CommandName = "CancelRow"
lb2.CommandArgument = "'<%#Eval('tripID')%>"
row.Cells(10).Controls.Add(lb2)
If row.Cells(8).Text = "Driver" Then
Dim lb As New LinkButton()
lb.ID = "lbEnd"
lb.Text = "End"
lb.CommandName = "EndRow"
row.Cells(9).Controls.Add(lb)
End If
End If
End Sub
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand
If (e.CommandName = "CancelRow") Then
Dim row As GridViewRow = e.CommandArgument
Dim index As String = Convert.ToString(DataBinder.Eval(row.DataItem, "tripID"))
ElseIf (e.CommandName = "EndRow") Then
End If
End Sub
I suspect the issue to be cause by Dim index As String = Convert.ToString(DataBinder.Eval(row.DataItem, "tripID")) however i have no idea how to solve it.
Hope you guys can help. Thanks!
If you try to debug the code, you will get that you are getting
Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.GridViewRow'
error at line
Dim row As GridViewRow = e.CommandArgument
Here you are trying to convert String into WebControls GridViewRow. In this case you should try
Dim row As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)
This will give you a GridViewRow and will evaluate value you are passing as CommandArgument.

Grid values deletion exception

I am trying to delete values from grid in VB.NET with following code:
Protected Sub gv_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gv.RowDeleting
Dim index As Integer = gv.EditIndex
Dim row As GridViewRow = DirectCast(gv.Rows(e.RowIndex), GridViewRow)
Dim id As Integer = Convert.ToInt32(gv.DataKeys(e.RowIndex).Value.ToString())
'Dim Id As Integer = Integer.Parse(DirectCast(gv.Rows(e.RowIndex).FindControl("txtId"), TextBox).Text)
gc.ExecuteCommand("delete from expence where id= '" & Id & "' ")
Response.Write("<script type='text/javascript' language='javascript'>alert('Data Updated')</script>")
gv.EditIndex = -1
bindGrid()
End Sub
It is giving me exception on line Dim id As Integer = Convert.ToInt32(gv.DataKeys(e.RowIndex).Value.ToString()) as follows:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I dont know why this exception is comming.
Please help me.
I think you haven't defined DataKeys property in gridview ,you should define DataKeys="id" in your gridview..

How to delete row from gridview's RowDataBound event

I am trying to delete a row from a gridview (based on a condition) and then add than row to another gridview inside of the "master" gridview's RowDataBound event. Originally I did not know that in order to call .DeleteRow(i) you needed to have an "ondelete" event handler. However, since all the gridview's .DeleteRow method does is call this event handler, I am confused as to how to use it. Can someone please help point me in the right direction?
Protected Sub grdProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdProduct.RowDataBound
' Grey out expired products
Dim row As GridViewRow
row = e.Row
Dim incomingDate As String
Dim incomingStatus As String = ""
incomingDate = row.Cells(3).Text.ToString()
incomingStatus = row.Cells(5).Text.ToString()
If (e.Row.RowType <> DataControlRowType.DataRow) Then
Exit Sub
End If
Try
Dim expDate As Date = incomingDate
If (expDate < DateTime.Today Or incomingStatus.Equals("D")) Then
'Create object for RowValues
Dim RowValues As Object() = {"", "", "", "", "", ""}
'Create counter to prevent out of bounds exception
Dim i As Integer = row.Cells.Count
'Fill row values appropriately
For index As Integer = 0 To i - 1
RowValues(index) = row.Cells(index).Text
Next
'create new data row
dProdRow = dProdtable.Rows.Add(RowValues)
dProdtable.AcceptChanges()
grdProduct.DeleteRow(e.Row.RowIndex)
End If
Catch ex As Exception
End Try
End Sub
Protected Sub grdProduct_Delete(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdProduct.RowDeleting
'Not sure what to do here
End Sub
The best way to do this is to manipulate this at the datasource level rather than manipulating the UI components themselves.
For example:
if(!IsPostback)
{
DataTable one = ...
DataTable two = ...
var removeRows = (from c in one.AsEnumerable()
where c.Field<DateTime>("incomingDate")< incomingDate ||
c.Field<string>("incomingStatus")=="D"
select c).ToList();
for(var item in removeRows)
{
two.ImportRow(item);
}
//now delete from initial table
foreach(var item in removeRows)
{
one.Rows.Remove(item);
}
//Now bind both grids
grid1.DataSource=one;
grid1.DataBind();
grid2.DataSource=two;
grid2.DataBind();
}
Update - Sample toy program in VB.NET Hopefully you can adapt it to your situation.
Sub Main
Dim one As New DataTable()
one.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = one.NewRow()
r.ItemArray = New Object() {i}
one.Rows.Add(r)
Next
Dim two As New DataTable()
two.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = two.NewRow()
r.ItemArray = New Object() {i}
two.Rows.Add(r)
Next
Dim removeRows = (From c In one.AsEnumerable() Where c.Field(Of Integer)("one") = 5).ToList()
For Each item As DataRow In removeRows
two.ImportRow(item)
Next
For Each item As DataRow In removeRows
one.Rows.Remove(item)
Next
End Sub
I just realized that you are using VB.NET. You should be able to translate the above from C# to VB.NET. The general idea is there, anyway.

Click event is not firing of dynamically added link button in grid view

I am writing the following code on the rowdatabound of the grid view and i am not getting the click event of link button
Protected Sub CoolGRDSourcedDetails_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles CoolGRDSourcedDetails.RowDataBound
Dim iLoop As Integer
Dim lbtnCountDetails As New LinkButton
e.Row.Cells.RemoveAt(1)
If e.Row.RowType = DataControlRowType.Header Then
For iLoop = 1 To (dscolumns / 2) - 1
e.Row.Cells(iLoop).Attributes.Add("colspan", "2")
If iLoop = 1 Then
e.Row.Cells(iLoop).Text = "Self"
Else
e.Row.Cells(iLoop).Text = "Child" & iLoop - 2
End If
Next
e.Row.Cells(iLoop).Text = "Total"
ElseIf e.Row.RowType = DataControlRowType.DataRow Then
For iLoop = 1 To dscolumns - 2
If iLoop Mod 2 <> 0 Then
e.Row.Cells(iLoop + 1).Text = Format(IIf(CInt(e.Row.Cells(iLoop).Text) <> 0, (CInt(e.Row.Cells(iLoop).Text) / value) * 100, 0), "0.00") & "%"
If CInt(e.Row.Cells(iLoop).Text) <> 0 Then
e.Row.Cells(iLoop).Controls.Add(lbtnCountDetails)
lbtnCountDetails.Text = e.Row.Cells(iLoop).Text
lbtnCountDetails.CommandArgument = "strstatus"
lbtnCountDetails.Attributes.Add("OnClick", "lbtnCountDetails_Click")
End If
End If
Next
End If
End Sub
'Click event is here
Protected Sub lbtnCountDetails_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim strStatus As String = CType(sender, LinkButton).CommandArgument
End Sub
Go to the below line in your code and make changes after that: -
ElseIf e.Row.RowType = DataControlRowType.DataRow Then
Actually you forgot to add an event handler to the event of LinkButton1, so you are not able to get the click event of the LinkButton.
The changes you have to make : -
If CInt(e.Row.Cells(iLoop).Text) <> 0 Then
LinkButton1.Text = e.Row.Cells(iLoop).Text
AddHandler LinkButton1.Click, AddressOf Me.LinkButton1_Click
LinkButton1.CommandArgument = e.Row.Cells(0).Text
e.Row.Cells(iLoop).Controls.Add(LinkButton1)
End If
Try it.
You can't add the event binding with an Attributes.Add. You can use the RowCommand event from the gridview. This link has a good example of using RowCommand.
Same question here.
Give a command name to your link button, like this
CommandName="Show"
and in the code behind, handle it as,
protected void gridviewReport_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Show")
{
// this will return the row index
int index = Convert.ToInt32(e.CommandArgument);
// your code goes here
}
}
Try this line:
Dim WithEvents lbtnCountDetails As New LinkButton

Help: Error = NullReferenceException was unhandled by user code

Any help would be appreciated... Code works cleanly until error...
Error occuring at line: SqlDataSource3.UpdateParameters("TechID").DefaultValue() = CInt(technicianRow("TechID"))
Here is full VB code:
Imports System.Data
Partial Class IncidentAssignment
Inherits System.Web.UI.Page
Public incidentRow As DataRowView
Public technicianRow As DataRowView
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Check to see if a incident has been selected
If GridView1.SelectedIndex = -1 Then
Button1.CommandName = ""
lblmessage.Text = "You must select an incident."
Else
Button1.CommandName = "NextView"
lblmessage.Text = ""
End If
End Sub
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
'Check to see if a incident has been selected
If GridView2.SelectedIndex = -1 Then
Button3.CommandName = ""
lblmessage2.Text = "You must select a technician."
Else
Button3.CommandName = "NextView"
lblmessage2.Text = ""
'Create second DataView
Dim techniciansTable As DataView = CType(SqlDataSource2.Select(DataSourceSelectArguments.Empty), DataView)
'Save the selected technician data row
'To the DataRowView object and to session state
technicianRow = techniciansTable(GridView2.SelectedIndex)
Session("Technician") = technicianRow
'Create DataView
Dim incidentsTable As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
'Save PageIndex and PageSize to variables.
Dim pageIndex As Integer = GridView1.PageIndex
Dim pageSize As Integer = GridView1.PageSize
'Calculate the value of the SelectedIndex
Dim selectedIndex As Integer = (pageIndex * pageSize) + GridView1.SelectedIndex
'Save the selected data row to the DataRowView
'object and to session state
incidentRow = incidentsTable(selectedIndex)
Session("Incident") = incidentRow
'Display output from the two DataRowView objects
Label1.Text = incidentRow("Name")
Label2.Text = incidentRow("ProductCode")
Label3.Text = technicianRow("Name")
End If
End Sub
Public Sub btnAssign_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAssign.Click
'Assign data from session state to
'the two DataRowView objects
***ERROR technicianRow = CType(Session("Technician"), DataRowView)
incidentRow = CType(Session("Incident"), DataRowView)
'Update the value of the two parameters to be
'used to store new information about the
'assigned technician
SqlDataSource3.UpdateParameters("TechID").DefaultValue() = CInt(technicianRow("TechID"))
SqlDataSource3.UpdateParameters("IncidentID").DefaultValue() = CInt(incidentRow("IncidentID"))
'Trap errors
Try
'Update the table.
SqlDataSource3.Update()
'Unselect the two GridView controls
GridView1.SelectedIndex = -1
GridView2.SelectedIndex = -1
'Rebind the GridView controls
GridView1.DataBind()
GridView2.DataBind()
'Move to the first view
MultiView1.ActiveViewIndex = 0
Catch ex As Exception
Session("Exception") = ex
Session("Page") = "~/Admin/IndicentAssignment.aspx"
Response.Redirect("~/ErrorMessage.aspx")
End Try
End Sub
Protected Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged
End Sub
End Class
Remove the parenthesis from ".DefaultValue()
do you have the parameters defined on the sqldatasource in the page??
UpdateParameters>
<asp:Parameter Name="SomeName" Type="String" />
<asp:Parameter Name="SomeDescription" Type="String" />
</UpdateParameters>

Resources