Button click is not firing in a multiview? - asp.net

I have one aspx page which contains 4 multiview controls and different views in each of them. In the first view which is the details view, I am entering some invoice details and checks the db for the datarow to appear along with the payment details.
The code works fine till it displays the datarow along with the payment control, but the payment control (user control) is not firing its validation controls properly (required field & regex controls). Besides the button click also not firing the validation code ,although it saves the data if I enter the correct details.
Could anyone of you please look into the below code and tell me whats wrong in it?.
Protected Sub cmdPay_Click(sender As Object, e As EventArgs) Handles cmdPay.Click
mvwDetails.Visible = False
Try
' If Not Page.IsPostBack Then
If Me.CreditCard1.CCNumber.Length < 14 Or Me.CreditCard1.CCNumber.Length > 16 Then
Me.lblError.Text = "Please enter Valid Card details"
Else
Dim result As DateTime = Conversions.ToDate("1/1/1900")
If Not DateTime.TryParse(Me.CreditCard1.CCExpireDate, result) Then
Me.lblError.Text = "Please enter the Valid Expiry Date"
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
ElseIf DateTime.Compare(result, DateTime.Today) < 0 Then
Me.lblError.Text = "Please enter the Valid Expiry Date"
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
ElseIf Me.CreditCard1.CVV Is Nothing Or Not Versioned.IsNumeric(DirectCast(Me.CreditCard1.CVV, Object)) Then
Me.lblError.Text = "Invalid credit card details."
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
ElseIf Strings.Len(Me.CreditCard1.CVV) > 4 Then
Me.lblError.Text = "Invalid cvv number."
Me.lblError.Visible = True
' mvwMakePayment.Visible = True
' mvwMakePayment.SetActiveView(vwMakePayment)
Else
Dim OrderID As String
OrderID = grdMain.Items(0).Cells(1).Text
If Page.IsValid Then
Dim dtOrderPerson As DataTable = Me.DataAction.GetDataTable("SELECT o.ID,o.BillToID,o.ShipToName,o.BillToCompanyID,o.OrganizationID,o.InvoiceNumber,OrderDate,GrandTotal,Balance,CurrencySymbol,NumDigitsAfterDecimal FROM " & Convert.ToString(Me.Database) & "..vwOrders o INNER JOIN " & Convert.ToString(Me.Database) & "..vwCurrencyTypes ct ON o.CurrencyTypeID=ct.ID where Balance > 0 AND o.OrderStatus <> 'Cancelled' And o.ID=" & CLng(OrderID), IAptifyDataAction.DSLCacheSetting.BypassCache)
If dtOrderPerson.Rows.Count > 0 Then
Me.mvwMakePayment.SetActiveView(vwMakePayment)
Me.mvwMakePayment.Visible = True
'lblkaj.Text = "returned a record"
FirstName = dtOrderPerson.Rows(0).Item("ShipToName").Trim.ToString()
Dim entityObject As AptifyGenericEntityBase = Me.AptifyApplication.GetEntityObject("Payments", -1)
entityObject.SetValue("EmployeeID", DirectCast(1, Object)) 'No web user is returned as the data is based on orderid and companyid , Employee id of the web user is 1 hence using the same
' entityObject.SetValue("EmployeeID", DirectCast(grdMain.Items(0).Cells(0).ToString(), Object))
entityObject.SetValue("PersonID", DirectCast(dtOrderPerson.Rows(0).Item("BillToID").ToString, Object))
entityObject.SetValue("CompanyID", DirectCast(dtOrderPerson.Rows(0).Item("BillToCompanyID").ToString, Object)) 'Me.dtOrders.Rows(0).Item("BilllToCompanyID").ToString
entityObject.SetValue("PaymentDate", DirectCast(DateTime.Today, Object))
entityObject.SetValue("DepositDate", DirectCast(DateTime.Today, Object))
entityObject.SetValue("EffectiveDate", DirectCast(DateTime.Today, Object))
entityObject.SetValue("PaymentTypeID", DirectCast(Me.CreditCard1.PaymentTypeID, Object))
entityObject.SetValue("CCAccountNumber", DirectCast(Me.CreditCard1.CCNumber, Object))
entityObject.SetValue("CCExpireDate", DirectCast(Me.CreditCard1.CCExpireDate, Object))
entityObject.SetAddValue("_xCCSecurityNumber", DirectCast(Me.CreditCard1.CVV, Object))
entityObject.SetValue("PaymentLevelID", DirectCast(1, Object))
' entityObject.SetValue("Comments", DirectCast("Created through the CGI e-Business Suite", Object))
entityObject.SetAddValue("_xConvertQuotesToRegularOrder", DirectCast("1", Object))
Dim genericEntityBase As AptifyGenericEntityBase = entityObject.SubTypes("PaymentLines").Add()
genericEntityBase.SetValue("Amount", DirectCast(dtOrderPerson.Rows(0).Item("Balance").ToString, Object))
genericEntityBase.SetValue("OrderID", DirectCast(dtOrderPerson.Rows(0).Item("ID").ToString, Object))
genericEntityBase.SetValue("Comments", DirectCast("Invoice paid from web", Object))
If entityObject.Save(True) Then
Dim dtPyments As DataTable = Me.DataAction.GetDataTable("select P.ID,P.PersonID,P.CompanyID,P.PaymentDate,Pl.OrderID,Pl.Amount from payment P inner join paymentdetail pl on P.id=Pl.paymentid where pl.orderid=" & CLng(OrderID))
' Me.grdReceipt.DataSource = DirectCast(dtPyments, Object)
' grdReceipt.DataBind()
' grdReceipt.Visible = False
lblInvo.Text = OrderID
lblPyNo.Text = dtPyments.Rows(0).Item("ID").ToString()
lblAmount0.Text = dtPyments.Rows(0).Item("Amount").ToString()
Dim amnt As Double = lblAmount0.Text
amnt = FormatNumber(amnt, 2)
lblAmount0.Text = amnt
' EmailID = txtEmail.Text.Trim.ToString
mvwMakePayment.Visible = False
mvwMessage.Visible = True
mvwMessage.SetActiveView(vwSuccessMessage)
Dim mailBody As New StringBuilder
mailBody.Append("Dear " & FirstName & ", ").AppendLine(Environment.NewLine)
mailBody.Append("Thank you, for your payment of invoice number " & lblInvo.Text & ". $ " & lblAmount0.Text & " " & "has been deducted from your nominated credit card. ").AppendLine(Environment.NewLine)
mailBody.Append("Your receipt number is " & lblPyNo.Text & ". Please keep this for your reference.").AppendLine(Environment.NewLine)
mailBody.Append("If you have any queries regarding this payment please contact our Accounts Receivable department on 04456666 and reference your invoice number.").AppendLine(Environment.NewLine)
' mailBody.Append("Receipt Number : " & lblPyNo0.Text)
sendEmail("Accounts Department", lblEmail.Text, "Payment Receipt’", mailBody.ToString)
' lblEmail.Text = EmailID
Else
mvwMessage.Visible = True
mvwMessage.SetActiveView(vwFailedMessage)
End If
End If
End If
End If
End If
'End If
Catch ex As ThreadAbortException
ExceptionManager.Publish(ex)
ProjectData.SetProjectError(DirectCast(ex, Exception))
ProjectData.ClearProjectError()
Catch ex As Exception
ProjectData.SetProjectError(ex)
ExceptionManager.Publish(ex)
ProjectData.ClearProjectError()
End Try
End Sub

check if you have proper validation group, also can happen if you are conditionally setting causes validation if so check that too.

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!

Neither a DataColumn nor a DataRelation - asp.net error

I'm getting this error:
banner_flag is neither a DataColumn nor a DataRelation for table temp
After searching, the error is apparently appearing because I'm referencing banner_flag, but it doesn't exist, but I've declared it in all the same places as intra_user (As an example).
Below is my code, any help is greatly appreciated. Thanks!:
Dim reason As String = ""
Dim banner_action As String = ""
Dim esr_link As String = ""
Dim seen_message AS String = ""
Dim last_updated AS String = ""
Dim daysSinceUpdated As Integer
Dim intra_user As String = ""
Dim banner_flag As String = ""
Sub Page_Load(ByVal Sender As Object, ByVal e As EventArgs)
Dim sc As Web.HttpContext = Web.HttpContext.Current
Dim updatePeriod As Integer = 90
Dim strConn As String = getStrConn(sc)
Dim rst As DataView
Dim strsql, last_updated, email_address As String
Dim update_required As String = ""
' - Really don't know what this is for... so I have commented it out.
' - Response.Write("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />hello no details")
' Check users last update to their email address
strsql = "select last_updated, email, esr_link, intra_user, banner_action, seen_message from user_group where id = " & Session("u_id") & " AND (esr_link <> 5)"
rst = GetDefaultView(strsql, strConn)
If (rst.count > 0) Then
' Get details for new banner check for launching windows at startup
If Not IsDBNull(rst(0)("banner_action")) Then
banner_action = rst(0)("banner_action").ToString
Else
banner_action = ""
End If
' Get details for seen message
If Not IsDBNull(rst(0)("seen_message")) Then
seen_message = rst(0)("seen_message").ToString
Else
seen_message = ""
End If
' Gets banner_flag value
If Not IsDBNull(rst(0)("banner_flag")) Then
banner_flag = rst(0)("banner_flag").ToString
Else
banner_flag = ""
End If
' Gets the ESR link value to check if the New User code needs to run
If Not IsDBNull(rst(0)("esr_link")) Then
esr_link = rst(0)("esr_link").ToString
Else
esr_link = ""
End If
' Gets the intra_user value
If Not IsDBNull(rst(0)("intra_user")) Then
intra_user = rst(0)("intra_user").ToString
Else
intra_user = ""
End If
' Grab users last_updated value if available
If Not IsDBNull(rst(0)("last_updated")) Then
last_updated = rst(0)("last_updated").ToString
Else
last_updated = ""
End If
' Grab users email address if available
If Not IsDBNull(rst(0)("email")) Then
email_address = rst(0)("email").ToString
email_address = Replace(email_address, "'", "")
Else
email_address = ""
End If
'Checks the email address to see if it is valid
If email_address <> "" Then
If IsEmailValid(email_address) = False Then
update_required = "true"
reason = "Your current Email address is invalid please update it." & vbCrLf
End If
Else
update_required = "true"
reason = "You have not entered a current Email address please add one." & vbCrLf
End If
'If it not empty then compare
If last_updated <> "" Then
last_updated = CDate(last_updated)
daysSinceUpdated = DateDiff("d", last_updated, Now())
If daysSinceUpdated > updatePeriod Then
update_required = "true"
reason &= "Your details have expired please check them to ensure they are up-to-date" & vbCrLf
End If
'If it empty then needs updating...
Else
update_required = "true"
reason = "Your details have expired please check them to ensure they are up-to-date" & vbCrLf
End If
rst.Dispose()
rst = Nothing
Session("checked_details") = "true"
If update_required = "true" Then
reason = Server.UrlEncode(reason)
'response.write(reason)
'Response.Write("<scr" & "ipt language='javascript'>findTop().submitURL('/sorce/app_centre/launch_form.aspx?fhandle=User_Details_Amendment&elemid=" & Session("u_id") & "&reason=" & reason & "');</scr" & "ipt>")
End If
Else
'Response.Write("<br /><br /><br /><br /><br /><br />hello details")
'Response.Write("<scr" & "ipt language='javascript'>findTop().submitURL('/sorce/app_centre/launch_form.aspx?fhandle=User_Details_Amendment&elemid=" & Session("u_id") & "&reason=" & reason & "');</scr" & "ipt>")
End If
End Sub
Function IsEmailValid(ByVal strEmail As String) As Boolean
Dim strArray() As String
Dim strItem As String
Dim i As Integer
Dim c As String
Dim blnIsItValid As Boolean
' assume the email address is correct
blnIsItValid = True
' split the email address in two parts: name#domain.ext
strArray = Split(strEmail, "#")
' if there are more or less than two parts
If UBound(strArray) <> 1 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' check each part
For Each strItem In strArray
' no part can be void
If Len(strItem) <= 0 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' check each character of the part
' only following "abcdefghijklmnopqrstuvwxyz_-."
' characters and the ten digits are allowed
For i = 1 To Len(strItem)
c = LCase(Mid(strItem, i, 1))
' if there is an illegal character in the part
If InStr("abcdefghijklmnopqrstuvwxyz_-.", c) <= 0 And Not IsNumeric(c) Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
Next
' the first and the last character in the part cannot be . (dot)
If Left(strItem, 1) = "." Or Right(strItem, 1) = "." Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
Next
' the second part (domain.ext) must contain a . (dot)
If InStr(strArray(1), ".") <= 0 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' check the length oh the extension
i = Len(strArray(1)) - InStrRev(strArray(1), ".")
' the length of the extension can be only 2, 3, or 4
' to cover the new "info" extension
If i <> 2 And i <> 3 And i <> 4 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' after . (dot) cannot follow a . (dot)
If InStr(strEmail, "..") > 0 Then
blnIsItValid = False
IsEmailValid = blnIsItValid
Exit Function
End If
' finally it's OK
IsEmailValid = blnIsItValid
End Function
Your sql statement is:
select last_updated, email, esr_link, intra_user, banner_action, seen_message from user_group where ...
Therefore there will be a column in the returned DataView for intra_user, which is present in the sql select, but not banner_flag, which is not present.

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

Invalid Cast Exception with Update Panel

On Button Click
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
MsgBox("INSIDE")
If SocialAuthUser.IsLoggedIn Then
Dim accountId As Integer = BLL.getAccIDFromSocialAuthSession
Dim AlbumID As Integer = BLL.createAndReturnNewAlbumId(txtStoryTitle.Text.Trim, "")
Dim URL As String = BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim)
Dim dt As New DataTable
dt.Columns.Add("PictureID")
dt.Columns.Add("AccountID")
dt.Columns.Add("AlbumID")
dt.Columns.Add("URL")
dt.Columns.Add("Thumbnail")
dt.Columns.Add("Description")
dt.Columns.Add("AlbumCover")
dt.Columns.Add("Tags")
dt.Columns.Add("Votes")
dt.Columns.Add("Abused")
dt.Columns.Add("isActive")
Dim Row As DataRow
Dim uniqueFileName As String = ""
If Session("ID") Is Nothing Then
lblMessage.Text = "You don't seem to have uploaded any pictures."
Exit Sub
Else
**Dim FileCount As Integer = Request.Form(Request.Form.Count - 2)**
Dim FileName, TargetName As String
Try
Dim Path As String = Server.MapPath(BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim))
If Not IO.Directory.Exists(Path) Then
IO.Directory.CreateDirectory(Path)
End If
Dim StartIndex As Integer
Dim PicCount As Integer
For i As Integer = 0 To Request.Form.Count - 1
If Request.Form(i).ToLower.Contains("jpg") Or Request.Form(i).ToLower.Contains("gif") Or Request.Form(i).ToLower.Contains("png") Then
StartIndex = i + 1
Exit For
End If
Next
For i As Integer = StartIndex To Request.Form.Count - 4 Step 3
FileName = Request.Form(i)
'## If part here is not kaam ka..but still using it for worst case scenario
If IO.File.Exists(Path & FileName) Then
TargetName = Path & FileName
'MsgBox(TargetName & "--- 1")
Dim j As Integer = 1
While IO.File.Exists(TargetName)
TargetName = Path & IO.Path.GetFileNameWithoutExtension(FileName) & "(" & j & ")" & IO.Path.GetExtension(FileName)
j += 1
End While
Else
uniqueFileName = Guid.NewGuid.ToString & "__" & FileName
TargetName = Path & uniqueFileName
End If
IO.File.Move(Server.MapPath("~/TempUploads/" & Session("ID") & "/" & FileName), TargetName)
PicCount += 1
Row = dt.NewRow()
Row(1) = accountId
Row(2) = AlbumID
Row(3) = URL & uniqueFileName
Row(4) = ""
Row(5) = "No Desc"
Row(6) = "False"
Row(7) = ""
Row(8) = "0"
Row(9) = "0"
Row(10) = "True"
dt.Rows.Add(Row)
Next
If BLL.insertImagesIntoAlbum(dt) Then
lblMessage.Text = PicCount & IIf(PicCount = 1, " Picture", " Pictures") & " Saved!"
lblMessage.ForeColor = Drawing.Color.Black
Dim db As SqlDatabase = Connection.connection
Using cmd As DbCommand = db.GetSqlStringCommand("SELECT PictureID,URL FROM AlbumPictures WHERE AlbumID=#AlbumID AND AccountID=#AccountID")
db.AddInParameter(cmd, "AlbumID", Data.DbType.Int32, AlbumID)
db.AddInParameter(cmd, "AccountID", Data.DbType.Int32, accountId)
Using ds As DataSet = db.ExecuteDataSet(cmd)
If ds.Tables(0).Rows.Count > 0 Then
ListView1.DataSource = ds.Tables(0)
ListView1.DataBind()
Else
lblMessage.Text = "No Such Album Exists."
End If
End Using
End Using
'WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.ReturnUrl("~/Memories/SortImages.aspx?id=" & AlbumID))
Else
'TODO:we'll show some error msg
End If
Catch ex As Exception
MsgBox(ex.Message)
lblMessage.Text = "Oo Poop!!"
End Try
End If
Else
WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.LoginWithReturnUrl("~/Memories/CreateAlbum.aspx"))
Exit Sub
End If
End Sub
The above code works fine.I have added an Update Panel in the page to avoid post back, But when i add the button click as a trigger
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" />
</Triggers>
in the update panel to avoid post back, i get the following error.This happens when i add the button click as a Trigger to the update panel.
The Request.Form returns a NameValueCollection which is accessible by the name of the key or the int indexer. It always returns a String and not an Integer.
Dim FileCount As String = Request.Form(Request.Form.Count - 2)
This is all intuition from the exception message, but on the line
FileCount As Integer = Request.Form(Request.Form.Count - 2)
It looks like Request.Form(Request.Form.Count - 2) is a string, and you're trying trying to assign a it to an integer type.
I don't know what you're trying to do, but the string looks like it contains "true" do you want the following?
FileCount As Integer += Boolean.Parse(Request.Form(Request.Form.Count - 2)) ? 1 : 0;

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

Resources