getting previous value before edition from textbox in gridview - asp.net

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

Related

Global Variables lose value in another event

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

VB.Net exception: Object reference not set to an instance of an object

I'm currently working on coding a web page for a school project. This site is supposed to be a simple online store where people can order prints of artwork. The specific page I'm working on has a Drop Down List (ddlArt) that is bound to my database and displays a list of the different art pieces available. When the user selects one of the items, all the information on that item is pulled from the database and displayed on the page in a variety of labels and such. The only thing is that I'm getting a null reference exception error saying "Object reference not set to an instance of an object" when I go to try to run the page. I got the same error on a homework assignment earlier in the year and managed to get it fixed, but I can't remember what I did and I can't get help from school until next week, so I thought I'd try my luck on here. Here's my code:
Private selectedArt As Art
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlArt.DataBind()
End If
selectedArt = Me.GetSelectedArt
lblArtID.Text = selectedArt.ArtID()
lblArtName.Text = selectedArt.ArtName()
lblCaption.Text = selectedArt.Caption()
lblDescription.Text = selectedArt.Description()
imgArt.ImageUrl = "~/images/" & selectedArt.FileName()
End Sub
Private Function GetSelectedArt() As Art
Dim artTable As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
artTable.RowFilter = "ArtID = '" & ddlArt.SelectedValue & "'"
Dim artRow As DataRowView = artTable(0)
Me.imgArt.ImageUrl = "~/images/" & artRow("FileName")
Dim art As New Art
art.ArtID = artRow("ArtID").ToString
art.ArtName = artRow("ArtName").ToString
art.Caption = artRow("Caption").ToString
art.Description = artRow("LongDescription").ToString
art.FileName = artRow("FileName").ToString
Return art
End Function
And here's the code for the Art class, in case anybody is interested:
Public Class Art
Public Property ArtID As Integer
Public Property ArtName As String
Public Property ArtType As String
Public Property Caption As String
Public Property FileName As String
Public Property Description As String
End Class
When I get the error, it highlights the artTable.RowFilter = "ArtID = '" & ddlArt.SelectedValue & "'" line in the GetSelectedArt function. I've tried comparing it to my corrected homework assignment that I mentioned, but I can't seem to find the problem. My VB is a little fuzzy because it's been awhile since I actually took the class. Any suggestions? Thanks a bunch!
If I understand your comment above correctly, on the initial page load there is nothing in the ddlArt, because the user must first choose an art type.
If that is correct, then your answer to my question is your answer.
For whatever reason (and without seeing at least the Select statement), artTbl is not getting instantiated, which is why you're seeing the Object reference not set to an instance of an object error.
One way to fix this (without knowledge of your SqlDataSource it's hard to give a precise answer) is to modify your Page Load method so that GetSelectedArt is only called when the user has selected an item from the drop down list. Right now GetSelectedArt is called every time the page loads.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlArt.DataBind()
Else
selectedArt = Me.GetSelectedArt
lblArtID.Text = selectedArt.ArtID()
lblArtName.Text = selectedArt.ArtName()
lblCaption.Text = selectedArt.Caption()
lblDescription.Text = selectedArt.Description()
imgArt.ImageUrl = "~/images/" & selectedArt.FileName()
End If
End Sub
However, the above modification will only prevent GetSelectedArt from being called on the initial page load. If your SqlDataSource.Select command is still returning nothing, then you're still going to have this problem.
A better solution would be to call the GetSelectedArt on the ddlArt.SelectedIndexChanged event handler. This way you'll know that you have (or should have) a valid SelectedValue from ddlArt.
Also, if you don't populate the drop down until the user selects an art type from the radio button list, why are you binding the drop down list on the initial page load (and what are you binding it to)? Or is the drop down list and detail information on a different page from the radio button list?
May be .. with ArtID as integer
artTable.RowFilter = "ArtID = " & format(ddlArt.SelectedValue)

Get cell value from specified column in a Gridview upon "RowUpdating" Event ASP.NET/VB

What i want to do is te following... i have a gridview that loads the data from a SQL server, i have the e.NewValue and e.oldValue to determine which data was being modified/updated but i need to get the unique record ID which is store in "ID_ControlCharts" column
So, can you provide a code snippet/brief explanation in how to get the value from "ID_controlCharts" already filled by the gridview when i updated 1 cell (e.new/old)???
Note: The index is not what i needed since the row can be deleted and the reference to that row is now lost, so since the "ID_controlCharts" is filled automatically by SQL server key, its perfect for my situation.
codebehind
If e.Equals("Control_SeqRef_CH") = False Then
Dim oldvalue As String = e.OldValues("Control_SeqRef_CH")
Dim newvalue As String = e.NewValues("Control_SeqRef_CH")
Dim rowindex As Integer = e.RowIndex
Dim IDfromcontrol as integer = ???
MsgBox(oldvalue)
MsgBox(newvalue)
MsgBox(rowindex)
Msgbox(IDfromcontrol)
Else
MsgBox("same")
End If
You have a couple of options:
If the ID_ControlCharts column is in the record, couldn't you fetch it from e.OldValues?
Dim IDfromcontrol = e.OldValues("ID_ControlCharts")
Failing that, if you set ID_ControlCharts as a column for the DataKeyNames property, you should be able to fetch it using the ItemIndex:
Dim IDfromcontrol = GridView1.DataKeys(e.ItemIndex).Values(0)
(This is all from memory, so the syntax may be a little off.)

RangeValidator not working when selecting DropDownList value using jQuery

I inherited a site which I am in the middle of updating which has a DropDownList and a RangeValidator assigned to it. The data is bound to the dropdown on Page_Load. The values are retrieved from the database so the value property of each item is set to the unique ID of the item in the DB.
The RangeValidator looks something like:
<asp:rangevalidator id="ddRangeValidator" runat="server" ControlToValidate="ddMenu" ErrorMessage="Please select value in range" MinimumValue="1" MaximumValue="100000" Type="Integer">*</asp:rangevalidator>
I have a method which automatically populates this value in jQuery e.g.
$("#ddMenu").val("An Option");
This works, however, when I try to post the page the range validation fails. Then even if I manually select that value, or select another valid value it still won't validate. The only way to make it validate is to select non-valid value and then re-selecting a valid one.
Any ideas?
Update
Here is the data binding code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load
If Not Page.IsPostBack Then
Dim ds As New DataSet()
Dim myDbObject As New myDbObject()
ds = myDbObject.ToDataSet() // retrieves all objects from the database
// store the results in a temporary view to filter
Dim dv As DataView
dv = New DataView(ds.Tables(0), "IsLive = True", "ID", DataViewRowState.CurrentRows)
Dim i As Integer = 0
ddMenu.Items.Add("Select a value")
ddMenu.Items.Item(0).Value = 0
// add all objects from filtered list into drop down menu
For i = 0 To dv.Count - 1
With ddMenu.Items
// add a new item
.Add(dv.Item(i).Item("Name"))
// set the Value property as unique ID of object
.Item(i + 1).Value = dv.Item(i).Item("ID")
End With
Next
End If
End If
Turns out it was an issue with my page loading twice...so now the issue is going to be tracking down why it is loading twice!
I guess the Range validator verifies the actual "value" of the dropdown list. May it be possible that by using jQuery to populate your dropdown the actual entry doesn't get a proper option "value"? Could you maybe post the rendered HTML code of your dropdown list?

Getting information (on click) that was used to programatically generate asp controls

How may one get information that was used to programatically generate asp controls?
For example, I pulled a DataTable of user objects from the database and have organized them on a page, listing groupings such as a list of employees directly under the employer for each employer. On the page, I list each user's Username as a LinkButton. When I click one of these employees, I want to redirect the page (which is easy) and set a session variable to the selected user's UserId (which seems not so easy). How can I pull this UserId value back? These elements are not hard-coded with nice names (as they are generated in a for each loop).
Code from comment below:
Dim lnkbtnPm As New LinkButton ' is my link button. '
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")
lnkbtnPm.CommandName = "CommandNameHere"
panelToAddControlTo.Controls.Add(lnkbtnPm)
Thanks :)
I think this is what you would use the CommandName and CommandArgument properties of the LinkButton for. Assign the user id as CommandArgument and a suitable string as CommandName and hook up the Command event to an event handler:
Sub LinkButton_Command(sender As Object, e As CommandEventArgs)
' e.CommandArgument will contain the user id '
End Sub
Update
The problem is that the event handler is never attached. Use AddHandler to do that:
Dim lnkbtnPm As New LinkButton
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")
lnkbtnPm.CommandName = "CommandNameHere"
AddHandler lnkbtnPm.Command, AddressOf LinkButton_Command
panelToAddControlTo.Controls.Add(lnkbtnPm)

Resources