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")
Related
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
I need to populate my gridview after I select a checkbox from checkboxlist. I'm trying to use a loop, I also need to hide the gridview if the user unchecks the checkbox. Im useing a sql statement to pull the data. The sql should pull whatever data is associated with the checked box
'Shows Books from selected Category
Protected Sub chkbListControl_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles chkListControl.SelectedIndexChanged
Dim sqlChecked As String = "select * " _
& "from Books, Categories " _
& "where Categories.CategoryCode=Books.CategoryCode " _
& "order by Title;"
Dim sqlUnChecked As String = "select * from Books where Categories.CategoryCode=Books.CategoryCode;"
Dim selectedIndex As Integer = chkListControl.SelectedIndex
Dim i As Integer
If (selectedIndex <> -1) Then
For i = 0 To chkListControl.Items.Count - 1
If chkListControl.Items(i).Selected Then
gvwBookList.DataSource = ReturnTable(sqlChecked)
gvwBookList.DataBind()
Else
gvwBookList.DataSource = ReturnTable(sqlUnChecked)
gvwBookList.DataBind()
gvwBookList.Visible = False
End If
Next
End If
End Sub
You need to modify your sqlchecked like this
dim selectedcategories as string=""
If (selectedIndex <> -1) Then
For i = 0 To chkListControl.Items.Count - 1
If chkListControl.Items(i).Selected Then
if selectedcategories="" then
selectedcategories=chkListControl.Items(i).value
else
selectedcategories &="," & chkListControl.Items(i).value
end if
End If
Next
End If
dim strSQL as string=""
if selectedcategories.trim<>"" then
strSQL = "select * " _
& "from Books, Categories " _
& "where Categories.CategoryCode=Books.CategoryCode and Categories.CategoryCode in (" & selectedcategories & ")" _
& "order by Title;"
else
strSQL="select * from Books where Categories.CategoryCode=Books.CategoryCode;"
end if
gvwBookList.DataSource = ReturnTable(strSQL)
gvwBookList.DataBind()
You can modify above code according to your requirement.
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
iam doing export functionality in asp.net1.1....
I want to highlight some records in red color when i export to excel...
following is my code to export records in excel but i want some records in red colors...
So how to do this plz help me out.
Public Shared Sub ExportToExcelInvitee(ByVal query As String, _
ByRef Response As System.Web.HttpResponse, _
Optional ByVal exportDataset As DataSet = Nothing)
Dim index As Integer
Dim colIndex As Integer
Dim columnCount As Integer
Dim excelDataSet As DataSet
Dim cnt As Integer
Const PROC As String = CLASSNAME & ".ExportToExcelInvitee"
Try
If IsNothing(exportDataset) Then
excelDataSet = ExecuteDataset(query)
Else
excelDataSet = exportDataset
End If
If Not IsNothing(excelDataSet) Then
If excelDataSet.Tables(0).Rows.Count <> 0 Then
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Response.AddHeader("Content-Disposition", "attachment; filename=List.xls")
Response.Write("<TABLE border=1>")
Response.Write("<TR>")
Response.Write("<TD><DIV align=center><B>Sr. No.</B></DIV></TD>")
columnCount = excelDataSet.Tables(0).Columns.Count - 1
For index = 2 To columnCount
Response.Write("<TD>" & _
"<DIV align=center>" + _
"<B>" & excelDataSet.Tables(0).Columns(index).ColumnName.ToString & "</B>" + _
"</DIV>" & _
"</TD>")
Next
Response.Write("</TR>")
Response.Write("<TR>")
' Loop to leave one empty line after header,
' Loopimg to add the TD with black boders which doens not get added if only TR added
For index = 2 To columnCount
Response.Write("<TD></TD>")
Next
Response.Write("</TR>")
cnt = 1
For index = 0 To excelDataSet.Tables(0).Rows.Count - 1
If Not (excelDataSet.Tables(0).Rows(index).RowState = DataRowState.Deleted) Then
Response.Write("<TR>")
Response.Write("<TD>" & _
"<DIV align=left>" & _
(cnt).ToString() & _
"</DIV>" & _
"</TD>")
For colIndex = 2 To columnCount
Response.Write("<TD valign=top>" & _
"<DIV align=left>" & _
excelDataSet.Tables(0).Rows(index).Item(colIndex).ToString() & _
"</DIV>" & _
"</TD>")
Next
Response.Write("</TR>")
cnt = cnt + 1
End If
Next
Response.Write("</TABLE>")
Response.End()
End If 'DataSet must contain data
End If 'DataSet must contain data
Catch ex As Exception
Call ErrorLog(PROC & ", " & ex.Source, ex.Message)
End Try
End Sub
In your case, that would be simply:
<TD style='color: red'>Some value</TD>
I can't see where you decide which cells should be highlighted red - however, since you're basically outputting an html table, you should be able to use standard markup to change either the 'color' or 'backgroundColor' attribute for that html element.
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.