ASP.Net Looping Through Gridview After adding Group Row - asp.net

In a GridView I am adding Grouping rows to the underlying table in the RowDataBound, but when I ApplyChanges and loop through each GridViewRow not all rows can be tested for TextBox value etc, the number of rows is reduced by the number of grouping rows inserted. Although it does loop through the grouping rows which I ignore, and misses the last n rows.
Private tmpSiteName As String = ""
Private Sub gvVehicles_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvVehicles.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
If tmpSiteName <> drv("lcname").ToString() Then
tmpSiteName = drv("lcname").ToString()
Dim tbl As Table = TryCast(e.Row.Parent, Table)
If tbl IsNot Nothing Then
Dim row As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim cell As New TableCell()
' Span the row across all of the columns in the Gridview
cell.ColumnSpan = Me.gvVehicles.Columns.Count
cell.Width = Unit.Percentage(100)
'cell.Style.Add("font-weight", "bold")
cell.Style.Add("background-color", "#f5f5f5")
cell.Style.Add("color", "#000000")
Dim span As New HtmlGenericControl("span")
span.InnerHtml = tmpSiteName
cell.Controls.Add(span)
row.Cells.Add(cell)
tbl.Rows.AddAt(tbl.Rows.Count - 1, row)
End If
End If
End If
End Sub
Private Sub ApplyChanges()
Dim AuctionDB As fleet.AuctionDB = New fleet.AuctionDB
Dim OldFleetNo As String = ""
Dim NewFleetNo As String = ""
Dim OldReserve As Integer = 0
Dim NewReserve As Integer = 0
Dim MTA As Long = 0
Dim Sitekey As String = ""
Dim vcaudit As Long = 0
Dim i As Integer = gvVehicles.Rows.Count
Try
For Each DRow As GridViewRow In gvVehicles.Rows
Sitekey = TryCast(DRow.FindControl("hiddenSitekey"), HiddenField).Value
MTA = Val(TryCast(DRow.FindControl("hiddenMTA"), HiddenField).Value)
strChange = ""
' The Grouping rows throw up funny results, but we can catch MTA = 0
If MTA > 0 Then
OldFleetNo = TryCast(DRow.FindControl("hiddenFleetNo"), HiddenField).Value
NewFleetNo = TryCast(DRow.FindControl("txtFleetNo"), TextBox).Text
If NewFleetNo <> OldFleetNo Then
vcaudit = AuctionDB.FleetUpdates(Sitekey, MTA, "FLEET NO", OldReserve, NewFleetNo, Session("user_name"))
updateCount += 1
strChange = "Fleet No. changed from " & OldFleetNo & " to " & NewFleetNo & "<br /><br />"
End If
End If
Next DRow
Catch ex As Exception
ShowMessage("Error: " & ex.Message, "alert-danger")
End Try
End Sub

Related

I can't FindControl in the more efficient way during RowDataBound event

I am working on filling two different labels from VB code behind. I currently have this working but I believe there is a much more efficient and better way of doing it. This is the only way I can find my labels without getting a Null reference exception. Again this works but what it does is go through each row multiple times (because of For Each Row....)
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
For Each Row As GridViewRow In GridView1.Rows
Dim HFO1AD As String = DirectCast(Row.FindControl("HFO1AD"), HiddenField).Value
Dim HFO2AD As String = DirectCast(Row.FindControl("HFO2AD"), HiddenField).Value
Dim HFO3AD As String = DirectCast(Row.FindControl("HFO3AD"), HiddenField).Value
Dim HFO4AD As String = DirectCast(Row.FindControl("HFO4AD"), HiddenField).Value
Dim HFO5AD As String = DirectCast(Row.FindControl("HFO5AD"), HiddenField).Value
Dim HFO6AD As String = DirectCast(Row.FindControl("HFO6AD"), HiddenField).Value
Dim OfficialsAccepted As Label = DirectCast(Row.FindControl("OfficialsAcceptedlbl"), Label)
Dim OfficialsNeeded As Label = DirectCast(Row.FindControl("OfficialsNeededlbl"), Label)
Dim RowID As String = DirectCast(Row.FindControl("IDlbl"), HyperLink).Text
Dim Cmd As SqlCommand
Dim dr As SqlDataReader
con.Open()
Cmd = New SqlCommand("Select OfficialsNeeded From Schedule WHERE ID ='" + RowID + "'", con)
dr = Cmd.ExecuteReader
dr.Read()
OfficialsNeeded.Text = dr(0).ToString
con.Close()
'Counting number of offiicials that have accepted
Dim N As Integer = 0
If HFO1AD = "Accept" Then
N = N + 1
End If
If HFO2AD = "Accept" Then
N = N + 1
End If
If HFO3AD = "Accept" Then
N = N + 1
End If
If HFO4AD = "Accept" Then
N = N + 1
End If
If HFO5AD = "Accept" Then
N = N + 1
End If
If HFO6AD = "Accept" Then
N = N + 1
End If
OfficialsAccepted.Text = N.ToString
Next
End Sub
From what I have read the way you are to do this is like the following but I get a null reference exception (Can't find the control)
Dim HFO1AD As String = DirectCast(e.Row.FindControl("HFO1AD"), HiddenField).Value
What am I doing wrong?
I figured it out.
I added the following if statement before my Dim statement and changed all my Dim statements back to look like this:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim HFO2AD As String = DirectCast(e.Row.FindControl("HFO2AD"), HiddenField).Value

Move grid rows up or down on button click

I have a grid that I am trying to move the grid rows either up or down based on button click. Here is what I have so far.
Protected Sub imgBtnMoveUp_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim imgBtn As ImageButton
Dim FirstRow As GridViewRow = gvQuoteSo.Rows(0)
Dim btnUp As Button = DirectCast(FirstRow.FindControl("MoveUp"), Button)
Dim gvrow As GridViewRow
Dim previousRow As GridViewRow
Dim index As Integer = 0
imgBtn = CType(sender, ImageButton)
If imgBtn.CommandName = "MoveUp" Then
index = Convert.ToInt32(imgBtn.CommandArgument)
gvrow = gvQuoteSo.Rows(index)
previousRow = gvQuoteSo.Rows(index - 1)
UpdatePanelGrid.Update()
End If
End Sub
When I click the button for up nothing hapens. I know this is just the move up function but if I can get help with that then the move down will answer itself. Thanks so much!
Explanations are given in comments.
Private Sub btnUp_Click(sender As Object, e As EventArgs)
Dim grid As DataGridView = Grid_view
Try
Dim totalRows As Integer = grid.Rows.Count ' will count the number of rows
Dim idx As Integer = grid.SelectedCells(0).OwningRow.Index ' row index of the selected cell
If idx = 0 Then ' for no rows selected
Return
End If
Dim col As Integer = grid.SelectedCells(0).OwningColumn.Index ' columns corresponding to the selected row
Dim rows As DataGridViewRowCollection = grid.Rows
Dim row As DataGridViewRow = rows(idx)
rows.Remove(row) ' Remove the corrent row
rows.Insert(idx - 1, row)' Re-insert the row
grid.ClearSelection()
grid.Rows(idx - 1).Cells(col).Selected = True
Catch
End Try
End Sub
Private Sub btnDown_Click(sender As Object, e As EventArgs)
Dim grid As DataGridView = Grid_view
Try
Dim totalRows As Integer = grid.Rows.Count
Dim idx As Integer = grid.SelectedCells(0).OwningRow.Index
If idx = totalRows - 2 Then
Return
End If
Dim col As Integer = grid.SelectedCells(0).OwningColumn.Index
Dim rows As DataGridViewRowCollection = grid.Rows
Dim row As DataGridViewRow = rows(idx)
rows.Remove(row)
rows.Insert(idx + 1, row)
grid.ClearSelection()
grid.Rows(idx + 1).Cells(col).Selected = True
Catch
End Try
End Sub

Get all selected values of CheckBoxList in VB.NET

I've used ASP's CheckBoxList control. Now what I want is to get the all selected values in VB code.
HTML
<asp:CheckBoxList ID="chkbxlst_Users" runat="server" RepeatColumns="2" RepeatDirection="Vertical" RepeatLayout="Table"></asp:CheckBoxList>
VB
Protected Sub btnSaveSetProject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSetProject.Click
Dim ds_selectedProjects As New DataSet
Dim eStr As String = String.Empty
Try
Catch ex As Exception
Me.ShowErrorMessage(ex.Message, "...btnSaveSetProject")
End Try
End Sub
On this Save button's click I want to get all the selected items' value and text in dataset.
try this..
For Each li As ListItem In chkbxlst_Users.Items
If li.Selected Then
// add item data into your dataset
Else
// do whatever you need
End If
End If
Next
You can try following code:
Protected Sub btnSaveSetProject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSetProject.Click
Dim ds_selectedProjects As New DataSet
Dim dt = New DataTable()
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcName)
Dim eStr As String = String.Empty
Try
For Each checkBox As CheckBox In chkbxlst_Users.Items
If (checkBox.Checked = True) Then
Dim dr As DataRow = dt.NewRow()
dr("ID") = checkBox.Text
dt.Rows.Add(dr)
End If
Next
ds_selectedProjects.Tables.Add(dt)
Catch ex As Exception
'Me.ShowErrorMessage(ex.Message, "...btnSaveSetProject")
End Try
End Sub
Try this code
Dim ds_selectedProjects As New DataSet
Dim dt_selectedProjects As New DataTable
dt_selectedProjects.Columns.Add("Value")
dt_selectedProjects.Columns.Add("Text")
Dim dr As DataRow
For i = 0 To chkbxlst_Users.Items.Count - 1
If chkbxlst_Users.Items(i).Selected Then
dr = dt_selectedProjects.NewRow()
dr("Value") = Val(chkbxlst_Users.Items(i).Value)
dr("Text") = chkbxlst_Users.Items(i).Text
dt_selectedProjects.Rows.Add(dr)
End If
Next
ds_selectedProjects.Tables.Add(dt_selectedProjects)
Try this
Dim str As [String] = ""
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
If str = "" Then
str = "'" + CheckBoxList1.Items(i).Value + "'"
Else
str += "," + "'" + CheckBoxList1.Items(i).Value + "'"
End If
End If
Next
'display in a textbox or lable with ID txtmsg
txtmsg.Text = str

gridview loop issue

I have a gridview with 4 columns, three of them are template fields where the user can enter the information needed and click a button to submit it to the database. I have 2 issues:
When I click my button to add a second row... the data in the first row posts
disappears. I want to be able to add the row without the first row of information
disappearing for multiple record entry situations. My code follows:
Private Sub SetInitialRow()
Dim dts As New DataTable()
Dim drs As DataRow = Nothing
dts.Columns.Add(New DataColumn("Approval Date", GetType(String)))
dts.Columns.Add(New DataColumn("Total Amount", GetType(String)))
dts.Columns.Add(New DataColumn("Comments", GetType(String)))
dts.Columns.Add(New DataColumn("Initials", GetType(String)))
drs = dts.NewRow()
drs("Approval Date") = String.Empty
drs("Total Amount") = String.Empty
drs("Comments") = String.Empty
drs("Initials") = String.Empty
dts.Rows.Add(drs)
ViewState("CurrentTable") = dts
gvOLIAdj.DataSource = dts
gvOLIAdj.DataBind()
End Sub
Private Sub AddNewRowToGrid()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
drCurrentRow = dtCurrentTable.NewRow()
drCurrentRow("Approval Date") = box1.Text
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
'dtCurrentTable.Rows(i - 1)("Initials") =
rowIndex += 1
Next
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentTable") = dtCurrentTable
gvOLIAdj.DataSource = dtCurrentTable
gvOLIAdj.DataBind()
End If
Else
Response.Write("ViewState is null")
End If
'Set Previous Data on Postbacks
SetPreviousData()
End Sub
Private Sub SetPreviousData()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dats As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
If dats.Rows.Count > 0 Then
For i As Integer = 0 To dats.Rows.Count - 1
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
box1.Text = dats.Rows(i)("Approval Date").ToString()
box2.Text = dats.Rows(i)("Total Amount").ToString()
box3.Text = dats.Rows(i)("Comments").ToString()
rowIndex += 1
Next
End If
End If
End Sub
Protected Sub btnAddNewRow_Click(sender As Object, e As EventArgs) Handles btnAddNewRow.Click
AddNewRowToGrid()
End Sub
When I try to write a loop that will loop through each of the template fields to grab
the data and put it into my database it doesn't recognize that I have data in the
template fields? This is what I have tried thus far to no avail...
Protected Sub btn_Update_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
For Each row As GridViewRow In gvOLIAdj.Rows
For Each gv As GridViewRow In gvOLIAdj.Rows
Dim appDt As String = (Rows(rowIndex).Cells(1).FindControl("txtAdjAppr")), TextBox)
Dim approvalDt As String = CType(gv.FindControl("txtAdjAppr"), TextBox).Text
Dim totalAmt As String = CType(gv.FindControl("txtAdjAmt"), TextBox).Text
Dim comments As String = CType(gv.FindControl("txtcmmts"), TextBox).Text
Dim intitials As String = DirectCast(gv.FindControl("total"), TextBox).Text
Next
End Sub
In your AddNewRowToGrid method you are doing the following:
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
What's wrong here is the updating of the row in dtCurrentTable.Rows(i - 1). You are updating the values in the row above that which you wish to update.

bulk copy duplicating each row when it is added to database

Why is my bulk copy duplicating each row, so in my database table the row shows twice.
Label1.Visible = True
Dim tourid As New List(Of String)
tourid.Add(TextBox1.Text)
Dim tasktype As New List(Of String)
Dim tourname1 As New List(Of String)
Dim tasknamelist As New List(Of String)
Dim dboxdates As New List(Of String)
Dim dates As New List(Of String)
Dim firstdates As New List(Of String)
Dim agent As New List(Of String)
Dim desc As New List(Of String)
Dim checkitem As ListItem
Dim departuredate As Date
For Each checkitem In dboxes.Items
If checkitem.Selected Then
departuredate = checkitem.Text
dboxdates.Add(departuredate)
For Each row As GridViewRow In GridView1.Rows
' Selects the text from the TextBox
Dim checkboxstatus As CheckBox = CType(row.FindControl("tasknamebox"), CheckBox)
If checkboxstatus.Checked = True Then
tasknamelist.Add(checkboxstatus.Text)
Dim dates1 As TextBox = CType(row.FindControl("tdays"), TextBox)
Dim gracep As TextBox = CType(row.FindControl("tgrace"), TextBox)
Dim aftersubtraction As DateTime
Dim fromatafter As DateTime
aftersubtraction = departuredate.AddDays(-dates1.Text)
fromatafter = aftersubtraction.AddDays(-gracep.Text)
firstdates.Add(fromatafter.ToString("MM/dd/yyyy"))
While fromatafter.DayOfWeek = DayOfWeek.Saturday OrElse fromatafter.DayOfWeek = DayOfWeek.Sunday
fromatafter = fromatafter.AddDays(-2)
End While
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
Dim txtdesc2 As TextBox = CType(row.FindControl("txtdesc"), TextBox)
desc.Add(txtdesc2.Text)
Dim tasktype1 As Label = CType(row.FindControl("tasktype"), Label)
Dim agentdlist As DropDownList = CType(row.FindControl("agentdlist"), DropDownList)
tasktype.Add(tasktype1.Text)
agent.Add(agentdlist.text)
Dim tourname As String
tourname = tname.Text
Dim sChars As String = " "
tourname1.Add(tourname.TrimEnd(sChars))
End If
Next
End If
If tasknamelist.Count > dboxdates.Count Then
Do
dboxdates.Add(checkitem.Text)
Loop Until tasknamelist.Count = dboxdates.Count
End If
If tasknamelist.Count > tourid.Count Then
Do
tourid.Add(TextBox1.Text)
Loop Until tasknamelist.Count = tourid.Count
End If
Next
table.clear()
For i As Integer = 0 To ((dates.Count) - 1)
Dim row = table.NewRow()
row("Tour") = tourid(i)
row("TourName") = tourname1(i)
row("Task") = tasknamelist(i)
row("Departure") = dboxdates(i)
row("Due Date") = dates(i)
row("Task Type") = tasktype(i)
row("Agent Name") = agent(i)
row("Completed") = "NO"
row("Description") = desc(i)
row("Orig Due") = firstdates(i)
table.Rows.Add(row)
Next
toptable.Visible = False
bottom.Visible = True
GridView2.DataSource = table
GridView2.DataBind()
Using bcp As SqlBulkCopy = New SqlBulkCopy(SqlDataSource2.ConnectionString)
bcp.ColumnMappings.Add(0, 1)
bcp.ColumnMappings.Add(1, 2)
bcp.ColumnMappings.Add(2, 3)
bcp.ColumnMappings.Add(3, 4)
bcp.ColumnMappings.Add(4, 7)
bcp.ColumnMappings.Add(5, 5)
bcp.ColumnMappings.Add(6, 10)
bcp.ColumnMappings.Add(7, 13)
bcp.ColumnMappings.Add(8, 6)
bcp.DestinationTableName = "dbo.stagingtasks"
bcp.WriteToServer(table)
End Using
Your doing a table.Rows.Add(row) and a New SqlBulkCopy()
They seem to be the same?

Resources