Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help creating text boxes and labels programmatically on web page 1

Status
Not open for further replies.

DougP

MIS
Dec 13, 1999
5,985
US
I have the controls in a SQL table and want to read them and make labels and text boxes on a page.
I also need to fill them with data after they are created.
Code:
      Me.lblHeading.Text = Session("formsProLoadForm")
        Dim MyTextBox As New TextBox()
        Dim MyLabel As New Label
        Dim LabelName As String = ""
        Dim TxtBoxname As String = ""
        
        Dim connStr As String = ConfigurationManager.ConnectionStrings("FormsConnectionString").ConnectionString
        Dim strConn As New SqlConnection(connStr)

        Dim Myform As New WebControls.FormView
        Myform.ID = "Myform"

        Dim objComm As SqlCommand
        Dim objReader As SqlDataReader
        Dim strSQL As String = "Select FieldName from forms_Main Order by UniqueID"
        strConn.Open()
        objComm = New SqlCommand(strSQL, strConn)
        objReader = objComm.ExecuteReader()
        If objReader.HasRows Then

            Do While objReader.Read()
                MyLabel.ID = "lbl" & objReader.GetString(0)
               [highlight #FCE94F] Myform.Page.Controls.Add(MyLabel)[/highlight]

                MyTextBox.ID = "txt" & objReader.GetString(0)
                Myform.Page.Controls.Add(MyTextBox)  

            Loop
        End If

DougP
 
the question is the title of the post
How do I create text boxes and labels on the fly.
2 how to a put text in the label
3 how do I put text in a text box one its created and has a variable for a name.

DougP
 
you wrote some code. Did you try it? Are you getting errors, not working at all?
 
error on yellow highlight
Object reference not set to an instance of an object.

DougP
 

You need to create new objects within your loop to add to the Form controls collection:

Code:
Dim MyTextBox As TextBox
Dim MyLabel As Label

Do While objReader.Read()
    MyLabel= New Label
    MyLabel.ID = "lbl" & objReader.GetString(0)
    MyLabel.Text = objReader.GetString(0)
    Myform.Controls.Add(MyLabel)

    MyTextbox = new Textbox()
    MyTextBox.ID = "txt" & objReader.GetString(0)
    MyTextBox.Text = objReader.GetString(0)
    Myform.Controls.Add(MyTextBox) 
Loop

Also your Form object must be runat="server" and your ID set must be unique.




Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
MarkSweetland, Ok so now I have this code but nothing shows on the scrren just a white page.
How to I make a run at server in code behind, I get an error
"A page can have only one server-side Form tag."
if I add HTML in this source code.
<form id="Myform" method="post" runat="server">
Code:
        Do While objReader.Read()
            MyLabel = New Label
            MyLabel.ID = "lbl" & objReader.GetString(0)
            MyLabel.Text = objReader.GetString(0)
            MyLabel.Style("Position") = "Absolute"

            MyLabel.Style("Top") = Trim(Str(TopPosition)) & "px"
            MyLabel.Style("Left") = "100px"
            MyLabel.BackColor = Drawing.Color.Azure
            Myform.Controls.Add(MyLabel)
            MyLabel.Visible = True

            MyTextBox = New TextBox()
            MyTextBox.ID = "txt" & objReader.GetString(1)
            MyTextBox.Text = objReader.GetString(1)
            MyTextBox.Style("Position") = "Absolute"

            MyTextBox.Style("Top") = Trim(Str(TopPosition)) & "px"
            MyTextBox.Style("Left") = "100px"
            Myform.Controls.Add(MyTextBox)
            MyTextBox.Visible = True
            TopPosition += 1
        Loop
        Myform.Visible = True

DougP
 
You should take out an css in your code and make sure the objects are being created and added to the form. I have a feeling your objects are positioned off of the screen.
 
I would use placeholders in the markup to hold your controls. Once you get the objects on screen, then apply your css clases. Here's a simple example:

Markup

Code:
 <%@ Page Language="vb" CodeBehind="default.aspx.vb" Inherits="Technical._default"   %>
<html>
    <head>
        <title>Tek-Tips</title>
    </head>
    <body>
        <form id="MyForm" runat="server">
            <asp:PlaceHolder runat="server" ID="phMainContent">
            </asp:PlaceHolder>
        </form>
    </body>
</html>

Code behind
Code:
Dim phContainer As PlaceHolder = Me.FindControl("phMainContent")
        Dim myLabel As Label
        Dim MyTextbox As TextBox

        If phContainer IsNot Nothing Then
            For i = 0 To 10
                myLabel = New Label
                myLabel.ID = "lbl" & i.ToString()
                myLabel.Text = "text"
                phContainer.Controls.Add(myLabel)

                MyTextbox = New TextBox()
                MyTextbox.ID = "txt" & i.ToString()
                MyTextbox.Text = "text"
                phContainer.Controls.Add(MyTextbox)

                phContainer.Controls.Add(New LiteralControl("<br />"))
            Next
        End If


Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
this is Visual Studtio .NET 2010 Pro by the way
the page does not display, just comes up with major crash page
Server Error in '/' Application.
--------------------------------------------------------------------------------
A page can have only one server-side Form tag.

If I take out the PlaceHolder HTML code I get a blank page again.

DougP
 
I took out the HTML
Ok I can see it's jumping over the > [highlight #FCE94F]If phContainer IsNot Nothing Then[/highlight]
So phContainer is nothing and it's not doing the for loop to create anything.



DougP
 

A page can have only one server-side Form tag.


It'll do that if you have a master page since that is where you define the form element and you try to add another form element on a page. If so, just add the

Code:
<asp:PlaceHolder runat="server" ID="phMainContent">
</asp:PlaceHolder>

to the page you're working.


Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
I'm going round in circles to nowhere !
getting error says: on yellow hightlite
-------------------------
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=formsPro
StackTrace:
at formsPro.FormViewer.Page_Load(Object sender, EventArgs e) in C:\dougcode\FormsPro\formsPro\FormViewer.aspx.vb:line 40
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
---------------------
here is all of the code
code behind
Code:
Imports System.Data.SqlClient
Public Class FormViewer
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.lblHeading.Text = Session("formsProLoadForm")
        Dim MyTextBox As New TextBox()
        Dim MyLabel As New Label
        Dim LabelName As String = ""
        Dim TxtBoxname As String = ""
        'load drop down list
        Dim connStr As String = ConfigurationManager.ConnectionStrings("FormsConnectionString").ConnectionString
        Dim strConn As New SqlConnection(connStr)
        Dim Myform As New WebControls.FormView
        Myform.ID = "Myform"
        Dim Counter As Integer
        'CREATE CONTROL
        'Myform = New WebControls.FormView
        ' Myform.Page.Controls.Add(Myform)
        Dim objComm As SqlCommand
        Dim objReader As SqlDataReader
        Dim strSQL As String = "Select top 1 FieldName from forms_Main Order by UniqueID"
        strConn.Open()
        objComm = New SqlCommand(strSQL, strConn)
        objReader = objComm.ExecuteReader()
        Myform = New WebControls.FormView
        If objReader.HasRows Then
            Do While objReader.Read()
                Counter += 1
                TxtBoxname = "txt"
                MyTextBox = New TextBox
                MyTextBox.ID = TxtBoxname & Trim(CStr(Counter))
                [highlight #FCE94F]Myform.Page.Controls.Add(MyTextBox)[/highlight]
                'MyLabel.ID = "lbl" & objReader.GetString(0)
                'Myform.Page.Controls.Add(MyLabel)
                'MyTextBox.ID = "txt" & objReader.GetString(0)
                'Myform.Page.Controls.Add(MyTextBox)

            Loop
        End If
    End Sub
End Class
HTML code
Code:
<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="FormViewer.aspx.vb" Inherits="formsPro.FormViewer" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>   
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 <asp:PlaceHolder runat="server" ID="phMainContent">
   <asp:Label ID="lblHeading" runat="server" Font-Bold="True" Font-Size="Large" 
        Text="."></asp:Label>
    <asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
&nbsp;<asp:TextBox ID="TextBox1" runat="server" Visible="False" Width="60px"></asp:TextBox>
    <asp:Button ID="btnSaveRecord" runat="server" Text="Save" />
</asp:PlaceHolder> 
 </asp:Content>

DougP
 


Not quite sure what you are trying to accomplish here. The FormView control is usually bound to a single data record using templates, and normally used with a Gridview in a Master/Detail type scenario. Adding a textbox to that control will fail anyway even without the null reference.

What is it that you are trying to show on the screen, and is it necessary to create the controls dynamically?


Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
I am trying to make a "forms" application in which anyone can make a form to replace a paper form. so instead of getting several paper forms when a person comes in to an office, they would be given a tablet computer instead. It would allow the office manager to enter the fields that go on the form. after that it would then create the form. so this part is trying to read the fields from the table and add labels and text boxes to the web page.

DougP
 

Think of the PlaceHolder as the "Form" that you're adding labels and textboxes to. It's just a parent container to add one or more other controls to. You're already defining the PlaceHolder, just find and use it:

Code:
 Me.lblHeading.Text = Session("formsProLoadForm")
        Dim phContainer As PlaceHolder = Me.FindControl("phMainContent")

        Dim MyTextBox As TextBox
        Dim MyLabel As Label

        Dim LabelName As String = String.Empty
        Dim TxtBoxname As String = String.Empty

        'Set connection
        Dim connStr As String = ConfigurationManager.ConnectionStrings("FormsConnectionString").ConnectionString
        Dim strConn As New SqlConnection(connStr)
        Dim Counter As Integer = 0

        'Get Data
        Dim objComm As SqlCommand
        Dim objReader As SqlDataReader
        Dim strSQL As String = "Select top 1 FieldName from forms_Main Order by UniqueID"
        strConn.Open()
        objComm = New SqlCommand(strSQL, strConn)
        objReader = objComm.ExecuteReader()
        If objReader.HasRows Then
            ' Create controls
            Do While objReader.Read()
                Counter += 1
                
                MyTextBox = New TextBox()
                MyTextBox.Text = "txt" & Counter.ToString()
                MyTextBox.ID = TxtBoxname & Trim(Counter.ToString())
                phContainer.Controls.Add(MyTextBox)

                MyLabel = New Label()
                MyLabel.ID = "lbl" & objReader.GetString(0)
                MyForm.Page.Controls.Add(MyLabel)
                phContainer.Controls.Add(MyTextBox)

            Loop
        End If

Then to get the data after the Save button is clicked:

Code:
 Private Sub btnSaveRecord_Click(sender As Object, e As System.EventArgs) Handles btnSaveRecord.Click
        Dim phContainer As PlaceHolder = Me.FindControl("phMainContent")
        For Each ctrl In phContainer.Controls
            ' Look for the Textbox Controls to save the data
            If TypeOf (ctrl) Is TextBox Then
                Response.Write("ID :" & ctrl.id & ", ")
                Response.Write(" Text: " & ctrl.Text & "<br />")
            End If
        Next
    End Sub


Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
Getting closer?
error on Placeholder line >>> Object reference not set to an instance of an object.
yellow highlight
Code:
....

       If objReader.HasRows Then
            ' Create controls
            Do While objReader.Read()
                Counter += 1

                MyTextBox = New TextBox()
                MyTextBox.Text = "txt" & Counter.ToString()
                MyTextBox.ID = TxtBoxname & Trim(Counter.ToString())
                [highlight #FCE94F]phContainer.Controls.Add(MyTextBox)[/highlight]
                MyLabel = New Label()
...



DougP
 
Additional error info.
also says:
Use the "New" keyword to create and instance of the object.

I tried this but to no avail

Code:
Dim phContainer As PlaceHolder = New PlaceHolder
        phContainer = Me.FindControl("PlaceHolder1")  ' My actual PlaceHolder on the form is called PlaceHolder1 

DougP
 

Then this is what the placeholder markup should look like:

Code:
<asp:PlaceHolder runat="server" ID="PlaceHolder1">
    <asp:Label ID="lblHeading" runat="server" Font-Bold="True" Font-Size="Large" Text="."></asp:Label>
    <asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server" Visible="False" Width="60px"></asp:TextBox>
    <asp:Button ID="btnSaveRecord" runat="server" Text="Save" />
</asp:PlaceHolder>


And you should find it using this code -- note the ID of the markup Placeholder matches that in FindControl() :

Code:
Dim phContainer As PlaceHolder = Me.FindControl("PlaceHolder1")





Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
OK I added the HTML markup as you have above.
then I changed the code to match the actual values, what I had above was a mis-mosh of $@%@$@.
I get no erros but: I only see a Save button and no text boxes or labels...
So Made the Visible properties "True" in the HTML markup for both the label and textbox. So now I see a label with the word label and a empty text box.
there should be 4 text boxes and 4 labels.
the labels should have the following, which is what it in the table.

SS [_________]
Fname [_________]
Lname [_________]
Addr [_________]

I can see that it is looping and the objReader.GetString(0) contrains teh 4 above values as it loops so theere is data? but nothing shows on screen
this is the problem I had on: 29 May 13 15:31
nothing shows up.

Code:
        Me.lblHeading.Text = Session("formsProLoadForm")
        Dim phContainer As PlaceHolder = Me.FindControl("PlaceHolder1")
        Dim Myform As WebControls.FormView = Me.FindControl("formview1")
        Dim MyTextBox As TextBox
        Dim MyLabel As Label
        Dim LabelName As String = String.Empty
        Dim TxtBoxname As String = String.Empty
        'Set connection
        Dim connStr As String = ConfigurationManager.ConnectionStrings("ConnectionStringDatabase1").ConnectionString
        Dim strConn As New SqlConnection(connStr)
        Dim Counter As Integer = 0
        'Get Data
        Dim objComm As SqlCommand
        Dim objReader As SqlDataReader
        Dim strSQL As String = "Select ColumnName from forms"
        strConn.Open()
        objComm = New SqlCommand(strSQL, strConn)
        objReader = objComm.ExecuteReader()
        If objReader.HasRows Then
            ' Create controls
            Do While objReader.Read()
                Counter += 1
                TxtBoxname = objReader.GetString(0)
                phContainer = New PlaceHolder
                MyTextBox = New TextBox()
                MyTextBox.ID = "TextBox1" & Counter.ToString   ' "txt" & TxtBoxname
                MyTextBox.Visible = True
                phContainer.Controls.Add(MyTextBox)
                MyLabel = New Label()
                MyLabel.ID = "Label2" & Counter.ToString ' "lbl" & TxtBoxname
                MyLabel.Text = TxtBoxname
                MyLabel.Visible = True
                phContainer.Controls.Add(MyLabel)
            Loop
        End If

DougP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top