I have a gridview and use a session to pass the variables from the page to an edit page. This works perfectly, until you search for a number. When you search the correct record displays in gridview, but when you click edit, it passes the wrong record.
Private Sub gridview1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
Session("wr_id") = GridView1.Rows(e.NewEditIndex).Cells(2).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(3).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(4).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(5).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(6).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(7).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(8).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(9).Text & "~\/~" & _
GridView1.Rows(e.NewEditIndex).Cells(10).Text & "~\/~"
Response.Redirect("WorkEdit.aspx")
End Sub
GRIDVIEW Page
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
Dim strPost As Boolean = HiddenSearch.Value
If strPost = True Then
Dim strNumber As String
Dim Dropdown As String
strNumber = Search_text.Text
Dropdown = Search_Field.SelectedValue
If Dropdown = "WO#" Then
Convert.ToInt32(strNumber)
End If
Try
SqlDataSource1.SelectCommand = "SELECT * FROM [WorkOrderLog] WHERE " + Dropdown + " = '" + strNumber + "' ORDER BY [WO#] DESC"
SqlDataSource1.Select(DataSourceSelectArguments.Empty)
SqlDataSource1.DataBind()
GridView1.DataBind()
Catch
'output messagebox for debug
Dim strPrompt As String
strPrompt = "Something bad happened, check search text and try again."
Dim strScript As String = "<script language=JavaScript>"
strScript += "alert(' " & strPrompt & "');"
strScript += "</script>"
Search_text.Focus()
End Try
Else
Search_text.Focus()
End If
End Sub
WORDEDIT Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'change submit button on mouseover events
Submit_Button.Attributes.Add("onmouseover", "this.src='../images/Submitdown.png'")
Submit_Button.Attributes.Add("onmouseout", "this.src='../images/Submitup.png'")
'change clear button on mouseover events
Clear.Attributes.Add("onmouseover", "this.src='../images/Cancel(down).png'")
Clear.Attributes.Add("onmouseout", "this.src='../images/Cancel(up).png'")
Call Keypress_ALegal()
Call Keypress_ASite()
errorWOName.Text = HiddenWOName.Value
errorLegalDesc.Text = HiddenLegalDesc.Value
errorLocationNumber.Text = HiddenLocationNumber.Value
errorDesc.Text = HiddenDesc.Value
errorSiteNumber.Text = HiddenSiteNumber.Value
If Not Page.IsPostBack Then
'Get session info
lblID.Text = "Session Variable Was Lost"
If (Session("wr_id") <> "") Then
Dim strSession As String = Session("wr_id")
Dim sessionArray As Array
'split session into array at ~\/~
sessionArray = Split(Session("wr_id"), "~\/~")
'assign textbox/dropdowns values passed from split variables
lblID.Text = sessionArray(0)
'WO Name
If sessionArray(1) = " " Then
WOName.Text = ""
Else
WOName.Text = sessionArray(1)
End If
Location.Text = sessionArray(2)
'LegalDesc
If sessionArray(3) = " " Then
LegalDesc.Text = ""
Else
LegalDesc.Text = sessionArray(3)
End If
'Trans ADDED
If sessionArray(4) = " " Then
TransADDED.Text = ""
Else
TransADDED.Text = sessionArray(4)
End If
'Trans Retired
If sessionArray(5) = " " Then
TransRETIRED.Text = ""
Else
TransRETIRED.Text = sessionArray(5)
End If
If sessionArray(6) = " " Then
Description.Text = ""
Else
Description.Text = sessionArray(6)
End If
If sessionArray(7) = "1/1/1900 12:00:00 AM" Or sessionArray(7) = " " Then
Started.Text = ""
Else
Started.Text = (CType((sessionArray(7)), DateTime).ToString("MM/dd/yyyy HH:mm tt"))
End If
If sessionArray(8) = "1/1/1900 12:00:00 AM" Or sessionArray(8) = " " Then
Completed.Text = ""
ElseIf sessionArray(8) = " " Then
Completed.Text = ""
Else
Completed.Text = (CType((sessionArray(8)), DateTime).ToString("MM/dd/yyyy HH:mm tt"))
End If
StakedBy.SelectedValue = sessionArray(9)
I realize not all of the code is pasted in here, because it would take too much space. Any Ideas? I'm guessing it has something to do with e.NewEditIndex
Your code looks fine. Is Session("wr_id") the actual code, or is "wr_id" mock-up code?
The reason I ask is because session values can either be accessed by a string or an index.
Session("id") will access the session variable with the "id" key
Session(8) will access the 9th element in the session
If you have code using Session(selectedID) and selectedID is a populated object variable, you will change the way you are accessing the session variables depending on whether selectedID is a number or a string
Update:
Look to see if you are binding anywhere else in your code (e.g. your Page_Load event). There is a good chance that you are re-binding the grid with new data before the control's edit event can fire
The solution to the problem was wrapping the pageload in a if, ispostback statement. Thank you for your help rkw.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then
If Search_text.Text = "" Then
SqlDataSource1.SelectCommand = "SELECT * FROM [WorkOrderLog] ORDER BY [WO#] DESC"
SqlDataSource1.Select(DataSourceSelectArguments.Empty)
SqlDataSource1.DataBind()
GridView1.DataBind()
Else
End If
End If
If Not IsPostBack Then
SqlDataSource1.SelectCommand = "SELECT * FROM [WorkOrderLog] ORDER BY [WO#] DESC"
SqlDataSource1.Select(DataSourceSelectArguments.Empty)
SqlDataSource1.DataBind()
GridView1.DataBind()
End If
End Sub
Related
First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!
I have a gridview that has textboxes where the user can type text to filter results. The textboxes are created dynamically by an extender below:
Imports Microsoft.VisualBasic
Namespace ControlExtenders
Partial Public Class GridView : Inherits System.Web.UI.WebControls.GridView
' METHOD:: OnLoad
Protected Overrides Sub OnLoad(ByVal e As EventArgs)
MyBase.OnLoad(e)
Me.SetPageSize()
End Sub
Protected Overloads Overrides Sub InitializeRow(ByVal row As GridViewRow, ByVal fields As DataControlField())
MyBase.InitializeRow(row, fields)
If row.RowType = DataControlRowType.Header Then
InitializeHeaderRow(row, fields)
End If
End Sub
Protected Overridable Sub InitializeHeaderRow(ByVal row As GridViewRow, ByVal fields As DataControlField())
' AddGlyph(Me, row)
AddFilters(row, fields)
End Sub
Protected Overridable Sub AddFilters(ByVal headerRow As GridViewRow, ByVal fields As DataControlField())
For i As Integer = 0 To Columns.Count - 1
If Not Columns(i).SortExpression = [String].Empty Then
AddFilter(i, headerRow.Cells(i), fields(i))
End If
Next
End Sub
Dim m_txtFilter As New Hashtable
Dim m_ddlFilter As New Hashtable
Protected Overridable Sub AddFilter(ByVal columnIndex As Integer, ByVal headerCell As TableCell, ByVal field As DataControlField)
If headerCell.Controls.Count = 0 Then
Dim ltlHeaderText As New LiteralControl(headerCell.Text)
headerCell.Controls.Add(ltlHeaderText)
End If
Dim ltlBreak As New LiteralControl("</br>")
headerCell.Controls.Add(ltlBreak)
Dim txtFilter As TextBox = Nothing
If m_txtFilter.Contains(columnIndex) Then
txtFilter = DirectCast(m_txtFilter(columnIndex), TextBox)
Else
txtFilter = New TextBox()
txtFilter.ID = (ID & "_txtFilter") + columnIndex.ToString()
'If field.ItemStyle.Width.Value <> 0.0R Then
' txtFilter.Style.Add(HtmlTextWriterStyle.Width, Convert.ToString(field.ItemStyle.Width.Value) & "px")
'ElseIf field.HeaderStyle.Width.Value <> 0.0R Then
' txtFilter.Style.Add(HtmlTextWriterStyle.Width, Convert.ToString(field.HeaderStyle.Width.Value) & "px")
'Else
'End If
m_txtFilter(columnIndex) = txtFilter
AddHandler txtFilter.TextChanged, AddressOf Me.HandleFilterCommand
Dim js As String
js = "javascript:" & Page.GetPostBackEventReference(Me, "#####buttonPostBack") & ";"
txtFilter.Attributes.Add("onchange", js)
End If
headerCell.Controls.Add(txtFilter)
End Sub
Private Sub HandleFilterCommand(ByVal sender As Object, ByVal e As EventArgs)
'this is required to make sure that unsetting of filter is also handled
Me.RequiresDataBinding = True
' Dim filterArgs As New FilterCommandEventArgs()
'filterArgs.FilterExpression = GetFilterCommand()
Dim filterString = GetFilterCommand()
'Me.OnFilterCommand(filterArgs)
End Sub
Protected Overloads Overrides Sub OnPreRender(ByVal e As EventArgs)
Dim filterCommand As String = GetFilterCommand()
If [String].IsNullOrEmpty(filterCommand) = False Then
ApplyFilterCommand(filterCommand)
End If
MyBase.OnPreRender(e)
End Sub
Public Function IsBoundColumn(ByVal objColumn As DataControlField) As Boolean
If Not objColumn.SortExpression = String.Empty Then
Return True
End If
End Function
Protected Overridable Function GetFilterCommand() As String
' Return ""
Dim filterCommand As String = ""
Dim i As Integer = 0
While i < Me.Columns.Count
If IsBoundColumn(Me.Columns(i)) Then
If Me.HeaderRow Is Nothing Then
i = i + 1
Continue While
End If
Dim headerCell As DataControlFieldHeaderCell = DirectCast(Me.HeaderRow.Cells(i), DataControlFieldHeaderCell)
Dim txtFilter As TextBox = DirectCast(m_txtFilter(i), TextBox)
Dim aColumn As DataControlField
'If Not (TypeOf Me.Columns(i) Is BoundField) Then
' i = i + 1
' Continue While
'End If
aColumn = DirectCast(Me.Columns(i), DataControlField)
If [String].IsNullOrEmpty(txtFilter.Text) Then
i = i + 1
Continue While
End If
Dim TextValue As String = txtFilter.Text
TextValue = TextValue.Replace("'", "''")
If [String].IsNullOrEmpty(filterCommand) Then
' Convert(TimespanColumn, 'System.String'
filterCommand = "Convert(" & aColumn.SortExpression + "," + Chr(39) + "System.String" + Chr(39) + ") like " + Chr(39) + "%" + TextValue + "%" + Chr(39)
Else
filterCommand += " AND " + "Convert(" & aColumn.SortExpression + "," + Chr(39) + "System.String" + Chr(39) + ") like " + Chr(39) + "%" + TextValue + "%" + Chr(39)
End If
End If
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Return filterCommand
End Function
Protected Overridable Sub ApplyFilterCommand(ByVal filterCommand As String)
Dim dsv As DataSourceView = Me.GetData()
Dim objDataSourceView As ObjectDataSourceView = dsv
objDataSourceView.FilterExpression = filterCommand
Me.DataBind()
If Me.Rows.Count = 0 Then
objDataSourceView.FilterExpression = ""
Me.ShowNotFoundMessage()
Me.DataBind()
End If
End Sub
Public Sub ShowNotFoundMessage()
Dim strMessage As String = "No records found for this specified search specification."
Dim strScript As String = "alert('" & strMessage & "'); "
If (Not Me.Page.ClientScript.IsStartupScriptRegistered("clientScript")) Then
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.GetType, "clientScript", strScript, True)
End If
End Sub
Public Sub SetPageSize()
'Skip hardcoded page size for role permission
If Me.PageSize <> 500 And Me.PageSize <> 25 Then
Me.PageSize = DBUtilities.GetPageSize
End If
End Sub
End Class
End Namespace
My question is, how do I access the values of the created textboxes in the calling page's code? I've tried the following but none of them work:
Label.Text = GridView1.FindControl("txtFilter3")
or
Dim row As GridViewRow = GridView1.Rows(0)
Label.Text = row.Cells(2).Text
or
Label.Text = C_C_C_CtlAccountProjectList1_GridView1_GridView1_txtFilter3
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
When I sort the grid view the UniqueID column remains where it is. I am using a separate page to edit and when I pass the UniqueID to that page to load the record it get the wrong record since the UniqueID was where it was before sorting. I read elsewhere about sorting and binding but it seems that is what I am doing. Any Ideas?
Private Sub GridView2_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView2.Sorting
Dim oldExpression As String = GridView2.SortExpression
Dim newExpression As String = e.SortExpression
If Session("SortExpression") <> e.SortExpression Then
Session("SortExpression") = e.SortExpression
ViewState("SortDirection") = Nothing
End If
If (ViewState("SortDirection")) Is Nothing Then
If ViewState("SortDirection") = "ASC" Then
ViewState("SortDirection") = "DESC"
Else
ViewState("SortDirection") = "ASC"
End If
Else
If ViewState("SortDirection") = "DESC" Then
ViewState("SortDirection") = "ASC"
Else
ViewState("SortDirection") = "DESC"
End If
End If
'12/10/13 DBP
Dim SQLOrderByString As String = ""
If e.SortExpression = "DateAwarded" Then
SQLOrderByString = " Order by CAST(CONVERT(VARCHAR,DateAwarded,101) AS smalldatetime) " & ViewState("SortDirection")
Else
SQLOrderByString = " Order by " & e.SortExpression & " " & ViewState("SortDirection")
End If
'note gblSQLAddNewString is created on page load so the column names are consistant
Dim SQLWhereString As String = "Where Organization = '" & Session("Organization") & "' "
Session("gblOrderByString") = SQLOrderByString
Dim SQLCombinedString As String = gblSQLAddNewString & SQLWhereString & SQLOrderByString
Me.GridView2.DataSource = PopulateGridwithSQL(SQLCombinedString)
Me.GridView2.DataBind()
End Sub
''----------------- Additional code ---------
Session("EditSQLRecordID") has the correct ID of the top row prior to clicking a column heading to sort. After sorting when clicking the edit button on the grid, I can see the correct ID in the grid. but when I pause the code and examine the Session("EditSQLRecordID") variable, it is incorrect. Therefore I am eding the wrong record. The edit is taking place on a different page.
Private Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged
Try
' get the RowID of the grid this allows the choosing of a particular column value in the row chosen
Dim RowID As Integer = GridView2.SelectedRow.RowIndex + 1
' Set session var to the SQL database record ID the last column (15) contains the SQL unique record ID
' this will be used to grab the record for editing
Session("EditSQLRecordID") = GridView2.Rows(GridView2.SelectedIndex).Cells(17).Text
Response.Redirect("EditGrid.aspx", False)
Catch ex As Exception
Dim ErrorTitle As String = "Error"
Dim PageName = System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.Url.AbsolutePath)
Dim Retval2 As String = ErrorTrap(PageName & " - " & System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ErrorTitle)
End Try
End Sub
--------------------- Editing ----------------
Private Sub GridView2_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView2.RowEditing
Try
' get the RowID of the grid this allows the choosing of a particular column value in the row chosen
Dim RowID As Integer = GridView2.SelectedRow.RowIndex + 1
' Set session var to the SQL database record ID the last column (15) contains the SQL unique record ID
' this will be used to grab the record for editing
Session("EditSQLRecordID") = GridView2.Rows(GridView2.SelectedIndex).Cells(17).Text
Response.Redirect("EditGrid.aspx", False)
Catch ex As Exception
Dim ErrorTitle As String = "Error"
Dim PageName = System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.Url.AbsolutePath)
Dim Retval2 As String = ErrorTrap(PageName & " - " & System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ErrorTitle)
End Try
End Sub
----------- Added --------------
Private Sub GridView2_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView2.PageIndexChanging
Me.GridView2.PageIndex = e.NewPageIndex
' 12/10/13 DBP
'note gblSQLAddNewString is created on page load so the column names are consistant
Dim SQLWhereString As String = "Where Organization = '" & Session("Organization") & "' "
' 12-24-13 DBP added global sort since the Pages were out of order when sorting
Dim SQLOrderByString As String = Session("gblOrderByString")
'"Order by " & e.SortExpression & " " & ViewState("SortDirection")
Dim SQLCombinedString As String = gblSQLAddNewString & SQLWhereString & SQLOrderByString
Me.GridView2.DataSource = PopulateGridwithSQL(SQLCombinedString)
Me.GridView2.DataBind()
End Sub
could you please help me find the reason of the mystery I've found?
In the below code, I create a DataTable and filter it. When I use filter1, everything works as expected.
When I use filter2, everything works as expected only if the SubsectionAmount variable is less than 10.
As soon as I set SubsectionAmount=10, the dr2 array returns Nothing.
I can't find what is wrong. Here is the code:
Imports System.Data
Partial Class FilterTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Call FilterTable()
End Sub
Sub FilterTable()
Dim dtSubsections As New DataTable
Dim SectionID As Integer, SubsectionID As Integer
Dim SubsectionAmount As Integer
Dim filter1 As String, filter2 As String
Dim rowID As Integer
Dim dr1() As DataRow, dr2() As DataRow
With dtSubsections
.Columns.Add("Section")
.Columns.Add("Subsection")
.Columns.Add("FieldString")
SectionID = 1
SubsectionAmount = 10 '9
For SubsectionID = 1 To SubsectionAmount
.Rows.Add(SectionID, SubsectionID, "abcd" & CStr(SubsectionID))
Next SubsectionID
For rowID = 0 To .Rows.Count - 1
Response.Write(.Rows(rowID).Item(0).ToString & " " _
& .Rows(rowID).Item(1).ToString & " " _
& .Rows(rowID).Item(2).ToString & "<BR>")
Next
SubsectionID = 1
filter1 = "Section=" & SectionID & " AND " & "Subsection=" & SubsectionID
filter2 = "Section=" & SectionID & " AND " & "Subsection=" & SubsectionID + 1
dr1 = .Select(filter1)
dr2 = .Select(filter2)
Response.Write(dr1.Length & "<BR>")
Response.Write(dr2.Length & "<BR>")
If dr1.Length > 0 Then
Response.Write(dr1(0).Item("FieldString").ToString & "<BR>")
End If
If dr2.Length > 0 Then
Response.Write(dr2(0).Item("FieldString").ToString & "<BR>")
End If
End With
End Sub
End Class
The line
"Section=" & SectionID & " AND " & "Subsection=" & SubsectionID + 1
looks dodgy to me (?)
Consider this snippet of code:
var i = 2;
string j = "Hello " + i + 1;
when you print j you will get "Hello21" and not "Hello3". The + operator applied on a string will accept any object on the right-hand side and uses them by calling ToString() on the object, hence making your int effectively a string. Now, I assume that in VB.Net it is quite similar, which may not be what you want.
Update
Apparently VB.Net does things differently, so happily ignore...
change your column add statements to the following so it does the comparisons correctly.
.Columns.Add("Section", GetType(Integer))
.Columns.Add("Subsection", GetType(Integer))
.Columns.Add("FieldString")