Asp.net 4, array resets for each run? - asp.net

I've created a very simple asp.net web page for generating some HTML. The idea is that each time the user clicks the button previous inputs gets stored into an array and is then listed together with the most recent input. The problem is that the array resets for each clicks, the same goes for the counter I've made (using "i" as integer and "i += 1" for each click.)
The result is that Case 0 is chosen every time, which of course isn't the plan.
Provided is the code. In advance, thanks.
Partial Class _Default
Inherits System.Web.UI.Page
Dim name, url, dive As String
Dim i As Integer
Dim rememberme(2) As String
Protected Sub btn_readmetoo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_readmetoo.Click
name = txt_name.Text
url = txt_url.Text
If i = 3 Then
i = 0
End If
Select Case i
Case 0
rememberme(0) = "Les også: " & "" & name & ""
txt_listurls.Text = "<p>" & rememberme(0) & "</p>"
Case 1
rememberme(1) = "Les også: " & "" & name & ""
txt_listurls.Text = "<p><ul><li>" & rememberme(0) & "<li>" & rememberme(1) & "</ul></p>"
Case 2
rememberme(2) = "Les også: " & "" & name & ""
txt_listurls.Text = "<p><ul><li>" & rememberme(0) & "<li>" & rememberme(1) & "<li>" & rememberme(2) & "</ul></p>"
End Select
i += 1
lbl_counter.Text = i
End Sub

The rememberme array is reset because they are not part of the Page ViewState. If you want to persist the array, then you can use the following syntax:
Protected Sub btn_readmetoo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_readmetoo.Click
name = txt_name.Text
url = txt_url.Text
If i = 3 Then
i = 0
End If
'recall array from ViewState
If ViewState("rememberme") IsNot Nothing Then
rememberme = ViewState("rememberme")
End If
Select Case i
Case 0
rememberme(0) = "Les også: " & "" & name & ""
txt_listurls.Text = "<p>" & rememberme(0) & "</p>"
Case 1
rememberme(1) = "Les også: " & "" & name & ""
txt_listurls.Text = "<p><ul><li>" & rememberme(0) & "<li>" & rememberme(1) & "</ul></p>"
Case 2
rememberme(2) = "Les også: " & "" & name & ""
txt_listurls.Text = "<p><ul><li>" & rememberme(0) & "<li>" & rememberme(1) & "<li>" & rememberme(2) & "</ul></p>"
End Select
i += 1
lbl_counter.Text = i
'Store array in ViewState
ViewState("rememberme") = rememberme
End Sub

Yes, each time the page reloads, the code starts over and creates a new page from scratch.
If you want to persist data from one page load to another, there are basically two solutions:
Put the data in the page (hidden field, cookie, et.c.) so that it's returned to the server when it requests the next page.
Put the data in a Session variable.

Related

Retrieving values from dynamically created controls

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!

ASP.NET 4.0 VB Grid view not getting ID after sorting

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

how to modify vbs to archive event logs

How to modify a VB script to archive event logs? I found one VB script working just fine to archive event logs to a network share folder, but I am not sure where to modify the VB script to:
Only collect system, application and security logs not all logs
How to make these archive logs with month, date and year and save them to the same folder daily and not overwrite them.
You need to change this line ("Select * from Win32_NTEventLogFile") Example
("Select * from Win32_NTEventLogFile where LogFileName='Application'")
Add in filter for the logs you wish to backup see http://social.technet.microsoft.com/Forums/scriptcenter/en-US/febbb896-e7fb-42c6-9b1b-6f3e3b293b22/event-viewer-log-script-only-working-for-application-event-log
OR
http://www.activexperts.com/activmonitor/windowsmanagement/scripts/logs/event/
This should help you.
See the following altered code for your requirements, will output required logs and save to a different folder each day.
VBS
Dim strComputer, objDir2
Dim current: current = Now
Dim strDateStamp: strDateStamp = dateStamp(current)
strComputer = "YourServer"
objDir2 = "Your File Server Path" & strDateStamp
Dim objDir1: objDir1 = "\\" & strComputer & "\c$\EVT"
clearEVTLogs = "No"
Set filesys=CreateObject("Scripting.FileSystemObject")
If Not filesys.FolderExists(objDir1) Then
createDir(objDir1)
If Not filesys.FolderExists(objDir2) Then
createDir(objDir2)
End If
strPath = objDir2 & "\"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate, (Backup, Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
("Select * from Win32_NTEventLogFile where LogFileName='Application' Or LogFileName='Security' Or LogFileName='System'")
For Each objLogfile In colLogFiles
strCopyFile = strDateStamp & "_" & strComputer & "_" _
& objLogFile.LogFileName & ".evt"
strBackupFile = "c:\EVT\" & strDateStamp & "_" _
& strComputer & "_" & objLogFile.LogFileName & ".evt"
strBackupLog = objLogFile.BackupEventLog _
(strBackupFile)
Call copyAFile(objDir1, strPath, strCopyFile)
If clearEVTLogs = "Yes" Then
objLogFile.ClearEventLog()
End If
Next
Function dateStamp(ByVal dt)
Dim y, m, d
y = Year(dt)
m = Month(dt)
If Len(m) = 1 Then m = "0" & m
d = Day(dt)
If Len(d) = 1 Then d = "0" & d
dateStamp = y & m & d
End Function
Function copyAFile( Byval strSourceFolder, Byval strTargetFolder, _
Byval strFileName)
Dim objFSO, booOverWrite, strResult
Set objFSO = CreateObject( "Scripting.FileSystemObject")
If objFSO.FileExists( strSourceFolder & "\" & strFileName) _
And UCase( strSourceFolder) <> UCase( strTargetFolder) Then
If objFSO.FolderExists( strTargetFolder) Then
Else
strResult = "The destination folder does not exist!"
'copyAFile = strResult
Exit Function
End If
If objFSO.FileExists( strTargetFolder & "\" & strFileName) Then
strResult = "The file exists, overwritten"
booOverWrite = vbTrue
Else
strResult = "The file does not exist, created"
booOverWrite = vbFalse
End If
objFSO.CopyFile strSourceFolder & "\" _
& strFileName, strTargetFolder & "\", booOverWrite
Else
strResult = "The source file does not exist, or " _
& "identical Source and Target folders!"
End If
End Function
Function createDir(strDir)
Set filesys=CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")
wscript.echo strDir
If Not filesys.FolderExists(strDir) Then
Set objFolder = objFSO.CreateFolder(strDir)
End If
End Function

ASP.net Gridview.. something weird

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

DataTable Filter mystery

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")

Resources