0

im new here and im having some problem with my vb.net code. I have dynamically created few textboxes on panel, and I want my code after submitting the form to save those values into database. Problem is that I just cannot find the way how to grab values from those texboxes. I tried everything that i found on internet but i still getting the error message "Object reference not set to an instance of an object". Can someone advice me what am i doing wrong. Here is the code how i created texboxes:

 for  i As Integer = 0 To cntPos -1
        Dim  txtJobTo as TextBox = new TextBox()
        txtJobTo.ID = "txtJobTo_" & jobID
        Dim label as Label = new Label()
        label.text = posPanel.Rows(i).Item("Position")

        pnlContainer.Controls.Add(label)
        pnlContainer.Controls.Add(new LiteralControl("</td><td>"))
        pnlContainer.Controls.Add(txtJobTo)
next

This line of code is shows those texboxes on page

<tr  bgcolor="#FFCC99"><td colspan="4">
 <asp:Panel ID="pnlContainer" runat="server" Visible="true"></asp:Panel></td></tr>
<tr><td colspan='6' align='center'> <asp:Button ID="cmdSave" Text="Save" ToolTip="cmdSave" CommandArgument="cmdSave_Click" runat="server" /></td></tr>

And this is part of the code that should save all data

Sub cmdSave_Click(ByVal sender As System.Object,  e As EventArgs) Handles cmdSave.Click  
   ...

        for  i As Integer = 0 To cntPosIns -1
            Dim strTo as TextBox = New TextBox()     
            posID = posIns.Rows(i).Item("ID_Pos")
           strTo.Text =CType(pnlContainer.FindControl("txtJobTo_" & posID.ToString()),TextBox).Text
....
'Insert into database
next

I always get error message on this line strTo.Text =CType(pnlContainer.FindControl("txtJobTo_" & posID.ToString()),TextBox).Text Can someone please give me some advice on how to fix this? What is the proper way to read value from dynamically created textboxes in this situation? Thank you

AnnaBell
  • 11
  • 3
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ňɏssa Pøngjǣrdenlarp Oct 28 '14 at 23:43
  • Sorry i'm a newbie in vb.net so I apologise if Im asking some basic things. I read the link that you had sent me, and I tried to change the code. I set PostBackUrl property of the submit button to another page. In that other page I have checked If PreviousPage IsNot Nothing Then If PreviousPage.IsCrossPagePostBack = True Then ... And I also changed Dim strTo as TextBox strTo.Text = CType(PreviousPage.FindControl("txtJobTo_" & posID.ToString()), TextBox).Text but I stll getting the same error message – AnnaBell Oct 29 '14 at 02:10

1 Answers1

0

there are two aspects to this I think. Dynamic controls are a bit of a minefield and can take a while to understand.

a) Make sue to create the dynamic controls and add them to the page during OnInit or CreateChildControls. Access the value in the event handler or during OnPreRender...otherwise you will have trouble using the standard TextBox.Text property to get the value. It's tricky using dynamic controls because the values are not present for the whole page lifecycle without inspecting the page.request property.

b) Personally, when I dynamically create input elements, I don't "let go" of them and rely on findControl to get a handle back onto them for me.

When I create controls dynamically, I store them in a look up e.g. a lovely Dictionary(of string, TextBox) which is accessible to the rest of the code, e.g. a property or member variable.

'  Lookup declared outside of the consuming methods so it is accessible to both
private dictControlsLookup as new dictionary(of string, textbox)

Sub YourSubName
     for  i As Integer = 0 To cntPos -1
            Dim  txtJobTo as TextBox = new TextBox()
            txtJobTo.ID = "txtJobTo_" & jobID
            Dim label as Label = new Label()
            label.text = posPanel.Rows(i).Item("Position")

            pnlContainer.Controls.Add(label)
            pnlContainer.Controls.Add(new LiteralControl("</td><td>"))
            pnlContainer.Controls.Add(txtJobTo)
            dictControlsLookup.Add(txtJobTo.ID, textJobTo)

    next
End Sub

    Sub cmdSave_Click(ByVal sender As System.Object,  e As EventArgs) Handles cmdSave.Click  
       ...

            for  i As Integer = 0 To cntPosIns -1
                Dim strTo as TextBox = New TextBox()     
                posID = posIns.Rows(i).Item("ID_Pos")
                dim ctlId as string = "txtJobTo_" & posID.ToString()
                If dictControlsLookup.ContainsKey(ctlId) Then
                     strTo.Text = dictControlsLookup(ctlId).Text
                End If
      ....
      'Insert into database
      next
   End Sub

Alternatively you could just iterate the dictControlsLookup.Values collection in save_click to access all the text boxes :-)

trucker_jim
  • 572
  • 3
  • 7
  • Thank you trucker_jim, this looks like something I was missing. I tried your example but after submitting i'm getting the error message " Name 'dictControlsLookup' is not declared." on this line " If dictControlsLookup.ContainsKey(ctlId) ". Btw i did declare dictControlLookup at the beginning like this Dim dictControlsLookup As New System.Collections.Generic.Dictionary(Of String, TextBox) – AnnaBell Oct 29 '14 at 17:34
  • Hi, if you declared the dictionary in the first sub or function, it won't be visible to cmdSave_Click. You need to declare it as a member variable that can be accessed from any method in your class. I'll edit the answer to try and make it absoulutely clear – trucker_jim Oct 30 '14 at 13:43
  • Thank you trucker_jim for your help, and I apologise for the late reply. I have tried code from above and it didn't show any error message which was great, but it also didn't write correct data into the database. By that I mean it is writing empty fields. It looks like it doesn't have stored Keys that i'm searching for it or it doesn't have anything stored in dictControlsLookup because when I write this code: If dictControlsLookup.ContainsKey(ctlId) Then strTo.Text = dictControlsLookup(ctlId).Text else strTo.Text = "didnt find it" End If. It always writes in database "didn't find it". – AnnaBell Nov 02 '14 at 00:33
  • Also when i try to loop For Each txtPairs As KeyValuePair(Of String, TextBox) In dictControlsLookup Dim tbx As TextBox = txtPairs.Value Dim tvalue As String = tbx.Text 'insert into db next I get zero inserts into db.But when i try to send it twice I got an error message "An item with the same key has already been added." So I am totally confused, everything is showing that dictionary is empty but then i get an error message that there is already a stored same value in db. Please any advise? – AnnaBell Nov 02 '14 at 00:35