Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls
Read values from dynamic controls Read values from dynamic controls
Read values from dynamic controls
Go Back  Xtreme Visual Basic Talk > > > Read values from dynamic controls


Reply
 
Thread Tools Display Modes
  #1  
Old 10-19-2008, 04:41 PM
mesaexplorerbc1 mesaexplorerbc1 is offline
Regular
 
Join Date: Jan 2004
Location: Gresham, OR
Posts: 61
Default Read values from dynamic controls


Hi!

I've searched up and down google and other places to try and figure this out, but I have not had any success.

I have created a page that queries a database for values. (QtyGood = x and QtyBad = x) Then the page dynamically creates a text box for each QtyGood and QtyBad Table Row.

(I.E. 6 Rows = 12 dynamically created textboxes.)

My problem now, is how do I access the .text and .id properties of these textboxes on a postback?

Links or examples are greatly appreciated.

Thanks!!!
Reply With Quote
  #2  
Old 10-19-2008, 08:53 PM
Targe Targe is offline
Contributor
 
Join Date: Nov 2006
Posts: 615
Default

By default textboxes do not clear on a postback so you should be able to call the .text property without problems in your code behind.

As far as their id and such, you can add that in when creating them at runtime. Another way (but this assumes these are the only textboxes on the form or you know of a way to filter out the ones you want), you can use a For Each ctl As Control In Me.Controls and use an If CType(ctl, Textbox) Then etc.
Reply With Quote
  #3  
Old 10-19-2008, 11:55 PM
mesaexplorerbc1 mesaexplorerbc1 is offline
Regular
 
Join Date: Jan 2004
Location: Gresham, OR
Posts: 61
Default

Thanks for the reply!

Here is the code I am using, but it's just test code to see if it's picking up the textboxes.

Code:
        If IsPostBack Then
            Dim Count As Integer

            For Each C As Control In Controls

                If TypeOf C Is TextBox Then

                    'MsgBox(CType(C, TextBox).Text)
                    Count += 1

                End If

            Next

            Response.Write("Count: " & Count.ToString)

        End If
The count is always 0. So the textboxes aren't being recreated in their exact state on a postback. What else should I look at to make sure I can access them when I click my "Submit" button. (The submit button will take the values in the textboxes and update a database.)
Reply With Quote
  #4  
Old 10-20-2008, 09:38 PM
Targe Targe is offline
Contributor
 
Join Date: Nov 2006
Posts: 615
Default

Oh right...I had a problem similar to that before but it was because I was using a Master/Child page. Try Parent.Controls just to try...if it does not work put a design time control on the page and see if it gets called in the For Each statement or check that Me.HasControls is returning true. If it is then I'm not sure why your other textboxes are not being found. I would need to see more of your code.
Reply With Quote
  #5  
Old 10-22-2008, 03:13 PM
geekzster geekzster is offline
Newcomer
 
Join Date: Aug 2007
Location: Tampa, FL. USA
Posts: 10
Default

An expanded example of your code would be useful.

I know for a fact that when you loop through your controls like that, it will not find the controls you think it's finding.

To demonstrate what I am saying, create a blank website with no master page and just a single page, default.aspx. Remove the <div> tags, so that it looks like this:

Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">

    </form>
</body>
</html>

Now in your code-behind, write the following:

Code:
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.HasControls Then
            Response.Write("Controls found:   " & Page.Controls.Count)
        End If
    End Sub
End Class
Now go ahead and run it. What you see is a count of 5 - these are the html controls that .Net created for you.

Now go ahead and add 1 textbox to the markup. Don't do anything with code-behind, and run it again.

The count stays the same.

So looping through the controls is useless. Also, in my experience, the .FindControl method is unreliable at best.

Your best bet (imo) is to create a datatable from the database. This way, regardless of postback, you can store your values. I would then look into creating a GridView, rather than managing a collection of textboxes.


Just my 2 cents.


however, if you really, _really_ want to use the textboxes and then loop through, try out this code I whipped up. the display is quite ugly, but I believe the concepts will be useful. there isn't any mark up to go with this except what .Net creates for you

Code:
Option Strict On
Option Explicit On
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        '    you have to build the controls before page load, otherwise they won't be there to check

        '    I do this to demonstrate how to loop through controls that are built at run-time,
        '    rather than at design time.
        Dim tb As TextBox
        Dim btn As New Button
        btn.ID = "btnPB"
        btn.Text = "PostBack"
        For i As Integer = 0 To 3
            tb = New TextBox

            '    the following line is key - it assumes that you have control over
            '    what the control is named originally.
            '    you should name it consistently, for looping.
            '    example:  TextBox0, TextBox1, etc.

            tb.ID = "TextBox" & i.ToString

            '    add it to the page
            '    must be added to a server control.
            '    for simplicity, I use form1
            form1.Controls.Add(tb)
        Next
        '    add the button control
        form1.Controls.Add(btn)
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' clicking the button will cause a postback event.
        If Page.IsPostBack Then
            If Page.HasControls Then
                '    set a var for generic controls and a var for textbox, used for looping then converting
                Dim c As Control
                Dim tb As TextBox
                '    set a gridview to display our ID/Value results
                Dim foo As New GridView

                '    set an ADO object to hold our ID/Value results as we loop
                '    we bind this to the gridview instantiated above
                Dim dt As DataTable = Me.BuildDT
                Dim dr As DataRow


                '    the following two lines are key - they asssume that you have control over
                '    what the control is named originally, as well as how many there will be.
                Dim dbCount As Integer = 3
                Dim dbID As String = "TextBox"

                '    begin looping
                For i As Integer = 0 To dbCount
                    '    instantiate a new datarow to hold values
                    dr = dt.NewRow
                    c = form1.FindControl(dbID & i.ToString)

                    If TypeOf c Is TextBox Then
                        '    convert to get access to control-specific methods
                        tb = CType(c, TextBox)
                        '     at this point, you have captured the text value
                        '    and you can populate a collection, datatable, or array with the values
                        '    for demonstration, I assign it to a datatable 
                        dr.Item("ID") = tb.ID.ToString
                        dr.Item("Value") = tb.Text.ToString
                        dt.Rows.Add(dr)

                    End If

                Next

                '    the datatable at this point is complete
                '    and you can loop through the rows to update the database, or pass it as an object
                '    to other methods for further processing.
                '    as an example :  :)
                For Each row As DataRow In dt.Rows
                    Response.Write("DataRow ID:  " & row.Item("ID").ToString & "  Value:  " & row.Item("Value").ToString)
                    Response.Write("<br />")
                Next
                '    now I bind the datatable to the gridview, for more demonstration
                foo.DataSource = dt
                foo.DataBind()
                form1.Controls.Add(foo)

            End If

        End If
    End Sub
    Private Function BuildDT() As datatable
        Dim dt As DataTable, dc As DataColumn
        dt = New DataTable
        dc = New DataColumn
        dc.ColumnName = "ID"
        dt.Columns.Add(dc)
        dc = New DataColumn
        dc.ColumnName = "Value"
        dt.Columns.Add(dc)
        Return dt
    End Function
End Class


Hope that helps someone.


Best,


G
Reply With Quote
  #6  
Old 10-22-2008, 08:56 PM
Targe Targe is offline
Contributor
 
Join Date: Nov 2006
Posts: 615
Default

Just to add further, there is a way to recursively call containers which they themselves have controls using the HasControls and pass the control back to the function, which will work 100% of the time to get back all your children containers. The problem with it though is that your case is very specific on what you need and you're saying you have no "good" way of knowing what these controls are called...

I'm thinking wrap them inside of a div that's specified to runat server and iterate through the div's controls (or any container will work). It should work and if it doesn't, I'll need to see your code.
Reply With Quote
  #7  
Old 10-29-2008, 05:17 AM
John_0025 John_0025 is offline
Freshman
 
Join Date: Sep 2003
Posts: 39
Default

How are you dynamically adding the textboxes? Server side or client side?

It looks like you problem is that you are trying to find the text boxes before they have been created. Remember in a postback we are creating a new instance of the page so you will need to dynamically add the textboxes again before you can use them.

Normally the value in the textbox will be stored in the view state and ASP will sort this all out for you so that TextBox.Text will contain the value entered by the user.

If you are adding the textboxes dynamically server side it will depend how it is done. I believe that controls have their value set from the view state prior to page load. So if you do it after this you'll need to pull the values out of the view state manually using the control ID.

If you are adding the textboxes client side then I think you'll need to come up with a way of letting the server know the id's of the controls you have added to the page.

If you can post some details on how you are adding these textboxes maybe I can help some more/at all.
Reply With Quote
  #8  
Old 10-29-2008, 06:43 AM
John_0025 John_0025 is offline
Freshman
 
Join Date: Sep 2003
Posts: 39
Default

I have made an example of how you might find the textbox values if you don't want to rebuild the textboxes during the postback.

Code:
    <form id="form1" runat="server">
        <div id="textBoxContainer" runat="server">
    
        </div>
        <asp:Button ID="addTB" runat="server" Text="Add text boxes" OnClick="GenerateTextBoxes" />
        <asp:Button ID="submit" runat="server" Text="Submit" />
    
        <asp:Literal runat="server" ID="enteredValues" />
    </form>
Code:
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Page.RegisterRequiresControlState(Me)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack Then
            For Each ClientID As String In dynamicTextboxState
                Dim value = Request.Form(ClientID)
                enteredValues.Text += value
            Next
        End If
    End Sub

    Private dynamicTextboxState As IList(Of String) = New List(Of String)()

    Protected Overloads Overrides Function SaveControlState() As Object
        Return dynamicTextboxState
    End Function

    Protected Overloads Overrides Sub LoadControlState(ByVal state As Object)
        dynamicTextboxState = DirectCast(state, IList(Of String))
    End Sub

    Protected Sub GenerateTextBoxes(ByVal sender As Object, ByVal e As EventArgs)
        Dim random As New Random()
        Dim count As Integer = random.[Next](2, 5)
        dynamicTextboxState = New List(Of String)()
        For i As Integer = 0 To count - 1
            Dim tb As New TextBox()
            textBoxContainer.Controls.Add(tb)
            dynamicTextboxState.Add(tb.UniqueID)
        Next
    End Sub
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls Read values from dynamic controls
Read values from dynamic controls
Read values from dynamic controls
 
Read values from dynamic controls
Read values from dynamic controls
 
-->