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 SkipVought 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
0
36
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
 
With the "New" PlaceHolder, you're creating a whole new control that is never added to the Page. The PlaceHolder is already defined in the markup.

Code:
Me.lblHeading.Text = Session("formsProLoadForm")
        Dim phContainer As PlaceHolder = Me.FindControl("PlaceHolder1")
        [COLOR=#EF2929][s]Dim Myform As WebControls.FormView = Me.FindControl("formview1")[/s][/color]       
        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)
                [COLOR=#EF2929][s]phContainer = New PlaceHolder[/s][/color]                
                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


Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
Ok so when I REM out the lines.
I get "new" error again (yellow highlight) which is why I added the phContainer = New PlaceHolder line
and the rest of the "NEW" lines there, it "barked" on each one of them.

I think there is no way to add stuff on the fly in a WEB page.

Code:
Error:
System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=forms
  StackTrace:
       at forms._Default.Page_Load(Object sender, EventArgs e) in C:\Users\z533560\Documents\Visual Studio 2010\Projects\forms\Default.aspx.vb:line 41
       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:

Code:
   location of error
    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
                [highlight #FCE94F]phContainer.Controls.Add(MyTextBox)[/highlight]
[/code]


DougP
 
what is the name of your placeholder in your HTML markup?
is it phMainContent, phPlaceholder, PlaceHolder1?
 
Ok. I think I see the problem. Adding dynamic controls to a page that uses a Master Page needs a couple of other steps.

First the Master Page Markup (not all of it, just the important parts)

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head id="MasterHead" runat="server">
    <title>
        <asp:ContentPlaceHolder ID="headContent" runat="server">
        </asp:ContentPlaceHolder>
    </title>
</head>
<body>
    <form id="MyForm" runat="server">
        <asp:ContentPlaceHolder ID="PageContent" runat="server">
        </asp:ContentPlaceHolder>
    </form>
</body>
</html>

And the Web Content Page that utilizes the Master Page (again, not all of it, just the important part)

Code:
<asp:Content ID="ContentPlaceHolderContent1" ContentPlaceHolderID="headContent" runat="server">
</asp:Content>
<asp:Content ID="ContentPlaceHolderContent2" ContentPlaceHolderID="PageContent" runat="server">
</asp:Content>

and now the code-behind

Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ' Find the ContentPlaceHolder Control on the Master Page
        Dim TheMasterContentControl As ContentPlaceHolder = Me.Master.FindControl("PageContent")

        ' If it was found...
        If TheMasterContentControl IsNot Nothing Then

            ' Declare a Label and a TextBox for Use later
            Dim TheRecordLabel As Label
            Dim TheRecordTextBox As TextBox

            ' Declare a Label for the Header
            Dim HeaderLabel As Label
            HeaderLabel = New Label
            HeaderLabel.Text = "Header Label Text"
            HeaderLabel.ID = "lblHeaderLabel"

            ' Create a new PlaceHolder Control and add a Label and literal
            Dim ThePlaceHolderContainer As PlaceHolder = New PlaceHolder
            ThePlaceHolderContainer.ID = "phMainContent"
            TheMasterContentControl.Controls.Add(HeaderLabel)
            TheMasterContentControl.Controls.Add(New LiteralControl("<br />"))

            For i = 0 To 10
                ' Create a new Label, set the properties, and add to placehodler
                TheRecordLabel = New Label
                TheRecordLabel.ID = "lbl" & i.ToString()
                TheRecordLabel.Text = "text"
                ThePlaceHolderContainer.Controls.Add(TheRecordLabel)

                ' Create a new textbox, set the properties, and add to placehodler
                TheRecordTextBox = New TextBox()
                TheRecordTextBox.ID = "txt" & i.ToString()
                TheRecordTextBox.Text = "text"
                ThePlaceHolderContainer.Controls.Add(TheRecordTextBox)
                ThePlaceHolderContainer.Controls.Add(New LiteralControl("<br />"))
            Next
            ' Add the placeholder to the Content Control (from Master)
            TheMasterContentControl.Controls.Add(ThePlaceHolderContainer)

            'Add a Button to use to Save the record after edit
            Dim btn As Button = New Button
            btn.ID = "btnSaveRecord"
            btn.Text = "Save"

            ' Add a handler for the new Button
            AddHandler btn.Click, AddressOf btnSaveRecord

            'Add the Button Control
            TheMasterContentControl.Controls.Add(btn)
        End If

    End Sub
    Private Sub btnSaveRecord()
        ' Get the Content Control 
        Dim TheMasterContentControl As ContentPlaceHolder = Me.Master.FindControl("PageContent")
        ' Get the PlaceHolder control from Content
        Dim phContainer As PlaceHolder = TheMasterContentControl.FindControl("phMainContent")
        ' Loop through all controls in the Container 
        For Each ctrl In phContainer.Controls
            ' Look for the Textbox Controls to save the data
            If TypeOf (ctrl) Is TextBox Then
                ' Do something with it
                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
 
Alrighty then!!! It did work, with some Minor tweaks;
I could not add anything to Site.master page
then the pageContent was not allowed is called mainContent now.

but it did put 10 text boxes and labels on the page so Now I can get back to designing.

So MarkSweetland have a star


DougP
 
MarkSweetland, I have two small issues :(
1st: If I click save, it leaves the data in the text boxes, is there a way to clear them out to add another new record?
I tried re-running the code in the page load but it created a whole other form. so ther wewre tow complete forms one on top of the other. Or make a new record button.

2nd: Align the left side of the text boxes. Right now everything is jammed together.
Just need code to do one I can figure them the rest out.
currently it looks like this:
Firstname[ ]
City[ ]
ST[ ]
Zip[ ]

prefer to have:
Firstname [ ]
City [ ]
ST [ ]
Zip [ ]

ST [ ] < is there a way to make these smaller?
Zip [ ]

Thank you so much this is fantastic so far :)




DougP
 
1.) You have to manually clear the textboxes.
2.) If you want to align the controls, then I suggest creating a table and adding the controls to it, then add the table to the placeholder.
 
can someone show me how to start a table within the code. I can make a table in HTML but how to add it to this??

DougP
 
My example is very simplistic but should help. You would need this in a loop:
Code:
      var tbl = new System.Web.UI.HtmlControls.HtmlTable();
        var row = new System.Web.UI.HtmlControls.HtmlTableRow();
        var td = new System.Web.UI.HtmlControls.HtmlTableCell();

        td.InnerText = "Dynamic Lable added to a Dynamic HTML Table";
        td.Attributes.Add("colspan", "2");
        row.Controls.Add(td);
        tbl.Controls.Add(row);

        row = new System.Web.UI.HtmlControls.HtmlTableRow();
        td = new System.Web.UI.HtmlControls.HtmlTableCell();
        td.Attributes.Clear();
        td.InnerText = "Row 1 / Col 1";
        row.Controls.Add(td);
        td = new System.Web.UI.HtmlControls.HtmlTableCell();
        td.InnerText = "Row 1 / Col 2";
        row.Controls.Add(td);
        tbl.Controls.Add(row);
        
        this.Controls.Add(tbl);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top