1

I simply can not wrap my head around this one.

I have 1 input box (textbox1) and many textboxes that show data from database, after value in textbox1 is entered data is shown and textbox1 is emptied so that another value could be entered and so on.

I also have second button for editing values in those other textboxes (that are enabled for that purpose) so when I decide to change those values and with that change them in database I need that value from textbox1 so that I could identify position of data in database.

I can not figure out how to store that value in Button1_click so that I can call it in a Button2_click. I know I can not set it out of the sub. I've tried to set another sub to store textbox1 value and to call in both buttons but that didn't work.

Jovica
  • 450
  • 9
  • 32

1 Answers1

1

.NET provides you with a number of options which will persist the data from textbox1 across postbacks. In your case I would personally opt for a hiddenfield.

Simply add a hiddenfield (I've named this Hiddenfield1 in my example for consistency) to your markup that will contain the most recent value of textbox1 at the time that your Button1_click is executed:

<asp:Hiddenfield id="Hiddenfield1" runat="server" />

And then for your event handlers:

Sub Button1_click(sender As Object, e As EventArgs)
    Hiddenfield1.Value = Textbox1.Text
    'Add your code to grab data from your database here.
End Sub

Sub Button2_click(sender As Object, e As EventArgs)
    'You still have access to the value stored in Hiddenfield1 here, do with it as you please!
End Sub

There are many answers around about persisting state across post backs (here, for example).

Another common approach would be to use the viewstate directly, but I would prefer the hiddenfield approach as it utilises the viewstate but does the (very slightly) hard work for you.

Community
  • 1
  • 1
jfsoul
  • 53
  • 6
  • But how to declare that variable? Dim HiddenField1 = New HiddenField() doesn't work for Button2. Sorry for newbie questions? – Jovica Mar 16 '14 at 09:07
  • 1
    I figure it out with Session.Add – Jovica Mar 16 '14 at 10:01
  • I've edited the post to include declaration of the hiddenfield, although it seems you've chosen a different method anyway. One advantage to the hiddenfield is that the value will be available client side if you ever need it. – jfsoul Mar 16 '14 at 10:09