Global Variables lose value in another event - asp.net

I have following global variables
Dim cardNumber As String
Dim txnAmount As String
Dim TerminalID As String
Dim CurrencyCode As String
And Values are assigned on a click Event from the result set returned from SP
dsCards = Utilities.GetVirtualResultNew(txtCardNumber.Text.Trim)
grdTransactionResultSearch.DataSource = dsCards
grdTransactionResultSearch.DataBind()
cardNumber = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("pan")), "", dsCards.Tables(0).Rows(0).Item("pan"))
txnAmount = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("TotalAmount")), "", dsCards.Tables(0).Rows(0).Item("TotalAmount"))
TerminalID = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("TerminalID")), "", dsCards.Tables(0).Rows(0).Item("TerminalID"))
CurrencyCode = IIf(IsDBNull(dsCards.Tables(0).Rows(0).Item("CurrencyCode")), "", dsCards.Tables(0).Rows(0).Item("CurrencyCode"))
I Debugged the code and I can see the values are assigned to them but when I try to access them in another button click event, They are empty
Here is my button click event where These variables are empty
Protected Sub btnAuthorize_Click(sender As Object, e As EventArgs) Handles btnAuthorize.Click
Utilities.InsertAuthorizedTransactions(cardNumber, txnAmount, TerminalID, CurrencyCode)
Label1.Visible = True
END Sub
Whats the problem with my code?

When a button is clicked, then a postback is performed (What is a postback?) which in this case will re-initliase your variables.
The preferred option is probably to store your variables in ViewState (What is ViewState?) in your first button click:
ViewState("cardNumber") = "foo"
ViewState("txnAmount") = "bar"
'etc.
And then access them in your second click.
Note also that you should not use the IIF function in VB.NET but you should instead use the If Operator

Related

Pass data from a Datagrid to a form and vice versa

I have a form called "FrmClientesEdicion" which has a postal code field, I am trying to open the postal code file and return to the first form the information selected in the second form from the datagrid. What happens is that with the code so far the info does not pass to me but rather it opens a new instance of the form "FrmClientesEdicion", help?
Open the postal code form "FrmCodigosPosAr" from a button in "FrmClientesEdicion" with this line:
Dim f As New FrmCodigosPosAr
f.ShowDialog()
Search in the form : "FrmCodigosPosAr" select a row and pass data (p.e Code, Name) again to the first one: "FrmClientesEdicion" with this lines:
Try
Dim F As New FrmClienteEdicion
With F
.TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString ' The code
.TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString ' The name city
.TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString ' The state
End With
Catch ex As Exception
MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()
This second point doesn't works open a new instance but don`t...
Thanks again
Note: The first form still open, never close it when I open the second one!
The pictures:
Open form 2
Then pass data from FORM2 to the FORM1 AGAIN
I answer myself in case someone needs it
In form2 (FrmCodigosPosAr)
Public Class FrmCodigosPosAr
Inherits System.Windows.Forms.Form
Public myCaller As FrmClienteEdicion
In form 1, (p.e in a Button to call form2 (FrmCodigosPosAr))
Dim myform As FrmCodigosPosAr
Private Sub BtnBuscaCP_Click(sender As Object, e As EventArgs) Handles BtnBuscaCP.Click
If myform Is Nothing Then
myform = New FrmCodigosPosAr
myform.myCaller = Me
End If
myform.Show()
End Sub
And in the form 2 (FrmCodigosPosAr) to pass data to Form1 (FrmClientesEdicion)
Try
If Not myCaller Is Nothing Then
myCaller.Text = Now.ToLongTimeString
myCaller.TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString
myCaller.TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString
myCaller.TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString
End If
Catch ex As Exception
MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()

ASP.NET DropDownList Selected Value With Enumeration

I'm using the settings in an enumeration to populate a dropdownlist in ASP.NET 4.0. The problem I'm having is that when I attempt to set a selected value other than first item, it throws an error telling me it cannot have more than one option selected.
Here's a sample of the code:
Public Shared Function ConvertEnumToArray(ByVal enumType As System.Type, _
Optional ByVal DefaultValue As String = "nodefault", _
Optional ByVal PromptValue As String = "", _
Optional ByVal PromptText As String = "") As ListItem()
Dim itemSelected As Boolean = False
Dim i As Int32 = 0
If Not enumType.IsEnum Then
Throw New Exception(String.Format("Type {0} is not an enumeration.", enumType.Name))
End If
'Dim itemValues() As Array = [Enum].GetValues(enumType)
Dim fields As FieldInfo() = enumType.GetFields()
Dim itemNames() As String = [Enum].GetNames(enumType)
Dim arr(itemNames.Length + 1) As ListItem
For Each field As FieldInfo In fields
If Not field.Name.Equals("value__") Then
Dim item As New ListItem(field.Name, field.GetRawConstantValue().ToString())
If item.Value = DefaultValue And DefaultValue <> "nodefault" Then
item.Selected = True
itemSelected = True
End If
arr(i) = item
i = i + 1
End If
Next
If PromptText <> "" Then
Dim item As New ListItem(PromptText, PromptValue)
If Not itemSelected Then
item.Selected = True
End If
arr(i) = item
End If
Return arr
End Function
Dim arrExtraChargesOptions() As ListItem
arrExtraChargesOptions = Enumerations.ConvertEnumToArray(GetType(Enumerations.MoneyRoomCourierExtraChargesOptions))
For Each li As ListItem In arrExtraChargesOptions
'since arrays double in capacity to store data, there may be nulls
If Not li Is Nothing Then
Me.drpMondayExtraCharges.Items.Add(li)
End If
Next
Me.drpMondayExtraCharges.ClearSelection()
Me.drpMondayExtraCharges.SelectedIndex = -1
Me.drpMondayExtraCharges.Items.FindByValue(Courier.MondayExtraCharge.ToString()).Selected = True
Despite clearing the selected value in multiple ways, the first item remains selected resulting in the error as mentioned above.
Other items that might help explaining how I ended up with the code above:
I'm setting the return type of the function to an array since that's the parameter type the AddRange function on the DropdownList.Items expects, but when I used that method, an exception resulted due to the NULLs in the array.
Before adding the ClearSelection() and SelectedIndex = -1 lines, my setting the selected value (either through the FindByValue as above or just directly setting the SelectedValue) resulted in my desired selected value being ignored.
Any thoughts? Thanks.
EDIT: I misspoke above (bad memory): Setting the SelectedValue directly results is what results in it being ignored. It has nothing to do with ClearSelection Or SelectedIndex =1 as I stated in the second bullet up above.
I found this issue (and I didn't provide enough code for you to find it yourselves).
Basically, I had a dropdownlist for each day of the week and the list items returned by ConvertEnumToArray above were added to each of the dropdowns. As a result, the selected item was changed on all the dropdown since the same list items were on each dropdown. Adding them to the dropdown as New Listitems solved the problem.

ASP.Net - Reducing repetitive code for validation - VB

I have a form with many drop down list boxes on. Each of which I am showing or hiding a row of a table based on its value then adding a requiredfieldvalidator to the text box contained in that row. I am doing this on the selectedindexchanged event of each drop down list, the code for which can be seen below:
Protected Sub cbOffCover_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbOffCover.SelectedIndexChanged
If cbOffCover.SelectedValue = "N" Then
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
End Sub
I then reuse this code for each drop down list to show/hide a differently named row and apply validation to a different text box.
My question being is there a better way of doing this? I don't know exactly how but I can't help but think I don't have to write this much code (or copy/paste) over and over again for each drop down list. Is it possible to write a function/class that will do the work and I can just call that instead? Might seem basic but i'm new to asp/vb. Many thanks
You can put it in a function that returns a boolean. When you call the function, pass it the combobox itself and whatever values you want to validate against. If it matches, return true. Try something like this:
Public Function ValidateComboBox(someComboBox as ComboBox, expectedValue as String)
Dim result as Boolean = False
If someComboBox.SelectedValue = expectedValue Then
result = True
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
Return result
End Function
Of course, modify it to fit your needs. Maybe you only return the value, and do the other stuff inside the control's SelectedIndexChanged method.

getting previous value before edition from textbox in gridview

I am applying edit functionality on gridview.
When my code's control is in rowupdating event, i am finding that i am getting previous value from textbox(i.e. value before i make edit in textbox).
Following is my code:
Protected Sub gvBooking_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvBooking.RowUpdating
'Dim name As String = DirectCast(gvBooking.Rows(e.RowIndex).FindControl("txtperson1"), TextBox).Text
Dim nname As String = (gvBooking.DataKeys(e.RowIndex).Values("person_name").ToString)
Dim id As Integer = Integer.Parse(gvBooking.DataKeys(e.RowIndex).Value.ToString)
Dim carname As String = gvBooking.DataKeys(e.RowIndex).Values("car_name").ToString
Dim carac As String = ""
'Dim sql As String = ""
'sql = "update dbo.tbl_Book set person_name='" + name + "',ac_type='" + carac + "' where booking_id = " + id.ToString
'gc.ExecuteCommand(sql)
'gvBooking.EditIndex = -1
'gc.BindGridView(gvBooking, "select * from tbl_Book")
End Sub
In this, if i edit person name from Henry to Scott and then press update button, then i finds through debugger that nname is having the value Henry only, which is the value before i make edit, instead it should have value Scott which i edited.
I am not understanding where i am making mistake.
Please help me.
After clicking Update, two events will be raised.
1.) GridView.Updating : Raised just before the Update is about to be committed.
In this event the data is still not updated in the Database. Basically this event is meant for some dynamic changes to be applied if required before the Update method actually commits the changed data to database.
2.) GridView.Updated
This event is raised immediately after data is updated. So it is in this event only that you put a debug symbol and check the Value. You will see your new value: Scott.
<asp:GridView ID="GridView1" runat="server" OnRowUpdated="GridView1_RowUpdated"></asp:GridView>
As you are checking the data when update is not made.That's why you are getting the original values only. Inside the GridView1_RowUpdated() method only check for the new values.
Also, still if you want to check your new values in Updating Event, Use GridViewUpdateEventArgs.NewValues Property [ e.Newvalues ] as : [ Check MSDN here ]
string s = e.NewValues[1].ToString(); // 2nd Column // c# sample

Changing DropDown Selected Item Based on Selected Value (ASP.NET)

I have a dropdown list on my page (ddlProgram) which is populated via a database query like so:
Using dbContext as IRFEntities = New IRFEntities
Dim getPrograms = (From p in dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddl.Program.DataBind()
End Using
So, for example, one might have a DataTextField of "Education" and an ID of "221".
Now, I prepopulate the form with information about the individual visiting the site (if available) - including the dropdown list like so:
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
ddlProgram.SelectedValue = getProspect.Program
End If
End If
The Program property contains a number that matches the ID of a Program. So, for example, this individual might have a Program of "221" which would match the "221" of Education mentioned above.
Currently the application successfully sets the SelectedValue to "221" for the DropDownList (ddlProgram), but the SelectedItem of the DDL remains the same (e.g., if it is initially "History" with an ID of "1" after the prepopulation it is "History" with an ID of "221").
What I'm trying to make happen is that the SelectedItem is updated to item which corresponds with the SelectedValue. So, in the end, if the individual has "221" for "Education" selected when the form is prepopulated they would see Education as the selected item and the selected value would be set correctly, whereas right now the form is showing the wrong SelectedItem but has the right SelectedValue behind the scenes.
Here is a more complete idea of the code flow from the Page_Load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
' If prospect is coming from unique url
Dim prospect_url As String = Page.RouteData.Values("value")
' Save prospect_url into session variable
Session("prospect_url") = prospect_url
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the programs dropdown.
Dim getPrograms = (From p In dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddlProgram.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the states dropdown.
Dim getStates = (From p In dbContext.IRF_States _
Order By p.name _
Select p)
ddlState.DataSource = getStates
ddlState.DataTextField = "name"
ddlState.DataValueField = "id"
ddlState.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Grab info. about prospect based on unique url.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
ddlProgram.SelectedValue = getProspect.program
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End If
End Using
End If
End Sub
What you're doing looks like it should work. If you put a breakpoint after the setting of the value and check the SelectedItem text and value, do they appear as expected or mismatched?
Use the Immediate Window to check:
ddlProgram.SelectedItem.Text
ddlProgram.SelectedItem.Value
If they appear the same then I would presume the binding code is being refired and the list is being regenerated with the first item being selected.
To check this put a break point on the binding code and see if it is fired more than once and correct the order of the methods appropriately.
ADDED:
If it works on your local environment it should work when published, if the code is the same? Looking at your code, I'd start by seperating out some of the databinding code into seperate methods rather than have everything in Page_Load, one becuase it's good practice and two because it will make debugging easier. Further than that I'm not sure what else to suggest.

Resources