Grid values deletion exception - asp.net

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..

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.

How to use ASP.NET replace command to insert variables?

<asp:TextBox ID="TESTBOX" runat="server">SOME TEXT Query=0 MORE TEXT</asp:TextBox>
Protected Sub btnReplace_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim QueryID As String
QueryID = Request.QueryString("Query")
Dim MyText As String = Me.TESTBOX.Text
Dim MyTextNew = MyText.Replace("Query=0", "Query=" & QueryID)
TESTBOX.Text = MyTextNew
End Sub
QUESTION
How do you replace text with a variable in ASP.NET VB?
"Replacing text with a variable" works.
Try this:
Dim myVar As Integer = 12
Dim MyTextNew = MyText.Replace("Query=0", "Query=" & myVar)
and it should work.
The problem in your code is that your request for the QueryString doesn't return a value. Check it with the stack trace or msgbox() and notice that it is null.

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.

loop through gridview and get data key value

I am trying to loop through the rows of my gridview and retrieve the data key value of each row and then execute some code to run sql queries. How can I get the data key value of each row in variable? right now I am receiving an error message saying:
value of type system.web.ui.webcontrols.datakey cannot be converted to integer.
Here is my code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each row As GridViewRow In GridView1.Rows
Dim therowindex As Integer = row.RowIndex
Dim theid As Integer = GridView1.DataKeys([therowindex])
'execute some more code running queries using the data key value.
Next
End Sub
You can iterate through the .Rows collection, and then find the row's DataKey value.
foreach(GridViewRow row in GridView1.Rows)
{
string theDataKey = GridView1.DataKeys[row.RowIndex].Value.ToString();
// Do something with your index/key value
}
You have to use Value property.
Dim theid As Integer = Integer.Parse(GridView1.DataKeys(therowindex).Value.ToString())

Issues with Asp.net Gridview Paging

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)

Resources