Page view counter

New empty textbox for every row in sql database?

Last post 07-24-2008 8:54 PM by limno. 12 replies.

Sort Posts:

  • New empty textbox for every row in sql database?

    07-24-2008, 2:04 PM
    • Loading...
    • chris_koehne
    • Joined on 02-13-2007, 1:29 PM
    • Posts 59
    • Points 8

    Hi,

    I try to find a way to generate dynamically TextBoxes on my side. Example:

    Database:

    ID            Name
    --------|---------------
    1      | Tom
    2      | Jerry
    3      | Lukas

    My page should like this:

    Tom:    emptyTextBox         'With TextBox.ID = 1
    Jerry:   emptyTextBox         'With TextBox.ID = 2
    Lukas:   emptyTextBox      'With TextBox.ID = 3

     

    Hope anybody can help me.

    Greetz, Chris
     

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 2:13 PM
    • Loading...
    • mellamokb
    • Joined on 02-09-2007, 10:44 PM
    • Posts 643
    • Points 3,559

    Hi,

    You could try a GridView with a column for the name and a column for your TextBox: 

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:BoundField DataField="Name" DataFormatString="{0}:" />
    <asp:TemplateField>
    <ItemTemplate>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>

    UPDATE: I don't believe you can set the TextBox ID in the ItemTemplate, as I think you will get an error.  However, you should be able to retrieve the ID's from the rows by other means.

    Cheers,

    ~ mellamokb

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 2:18 PM
    • Loading...
    • lotuzwine
    • Joined on 10-01-2007, 7:14 PM
    • Posts 109
    • Points 345

    actually, you can use ID in the ItemTemplate. To acess the textboxes, you have to implement the RowDataBound method and retrieve the TextBox with the GridViewRowEventArgs.Row.DataItem.FindControl([[TextBoxId]])

     regards

    Please, mark as answer if this post helped you
    "I am nobody
    Nobody is perfect
    Therefore, I must be perfect!"
  • Re: New empty textbox for every row in sql database?

    07-24-2008, 2:23 PM
    • Loading...
    • ecbruck
    • Joined on 12-30-2005, 7:39 PM
    • Des Moines, IA
    • Posts 9,159
    • Points 85,497
    • Moderator

    Here's an example for you: 

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Data.SqlClient;
    
    public partial class Posts_GeneralASPNET_DataPresentationControls_1295197 : System.Web.UI.Page
    {
    	protected void Page_Load(object sender, EventArgs e)
    	{
    		this.AddTextBoxes();
    	}
    
    	private void AddTextBoxes()
    	{
    		foreach (DataRow dr in this.GetData().Tables[0].Rows)
    		{
    			this.Form.Controls.Add(new LiteralControl(String.Format("{0}: ", dr["FirstName"])));
    			
    			TextBox txt = new TextBox();
    			txt.ID = String.Concat("txt", dr["EmployeeID"]);
    			this.Form.Controls.Add(txt);
    
    			this.Form.Controls.Add(new LiteralControl("&lt;br />"));
    		}
    	}
    
    	private DataSet GetData()
    	{
    		DataSet ds = null; 
    	
    		SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
    		SqlCommand cmd = new SqlCommand("SELECT * FROM [Employees]", conn);
    		SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    
    		try
    		{
    			conn.Open();
    
    			ds = new DataSet();
    			adapter.Fill(ds);
    		}
    		finally
    		{
    			if (conn != null) { conn.Close(); }
    		}
    
    		return ds;
    	}
    }
    Thanks, Ed

    Microsoft MVP - ASP/ASP.NET

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 3:11 PM
    • Loading...
    • chris_koehne
    • Joined on 02-13-2007, 1:29 PM
    • Posts 59
    • Points 8

     Hi,

     thank you all for the fast response. Can you help me also with an example in vb?

    Thank you again, Chris
     

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 3:38 PM
    • Loading...
    • chris_koehne
    • Joined on 02-13-2007, 1:29 PM
    • Posts 59
    • Points 8

     Some more informations about my problem...

    I have two tables in a database. In the first one there are stored the metadatanames, for example for an invoice

    ID | Metadatname
    ---|----------------------
    1 | creditor
    2 | invoice-nr
    3 | invioce-date

    On the webpage the user should enter for example:

    Label            TextBox
    --------------------------------------
    creditor:         "Microsoft"
    Invoice-nr:     "1234"
    Invoice-date: "2008-07-24"

    The labels in front of the textboxes should be created dynamically from table1. With the answers in the TextBoxes I want to start a Select in table2, for example:

    Select * From table2 where value1 like '%' + TextBox1.text + '%' OR value2 like '%' + TextBox2.text + '%' OR value3 like '%' + TextBox3.text + '%'

    Result should be a gridview like this:

     ID        Creditor   Invoice-nr   date              link to document
    -----------------------------------------------------------------------------------------------
    1         Microsoft   12345      2008-07-24   \\server\path\invoice.pdf

     

    My problem is just to create this dynamic page and use the text entrys of the user as search criteria in the select...

    Thanks, Chris 

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 3:44 PM
    • Loading...
    • ecbruck
    • Joined on 12-30-2005, 7:39 PM
    • Des Moines, IA
    • Posts 9,159
    • Points 85,497
    • Moderator

    Here you go: 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    	Me.AddTextBoxes()
    End Sub
    
    Private Sub AddTextBoxes()
    	For Each dr As DataRow In Me.GetData.Tables(0).Rows
    		Me.Form.Controls.Add(New LiteralControl(String.Format("{0}: ", dr("FirstName"))))
    
    		Dim txt As New TextBox()
    		txt.ID = String.Concat("txt", dr("EmployeeID"))
    		Me.Form.Controls.Add(txt)
    
    		Me.Form.Controls.Add(New LiteralControl("<br />"))
    	Next
    End Sub
    
    Private Function GetData() As DataSet
    	Dim ds As DataSet = Nothing
    
    	Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString)
    	Dim cmd As New SqlCommand("SELECT * FROM [Employees]", conn)
    	Dim adapter As New SqlDataAdapter(cmd)
    
    	Try
    		conn.Open()
    
    		ds = New DataSet()
    		adapter.Fill(ds)
    	Finally
    		If conn IsNot Nothing Then
    			conn.Close()
    		End If
    	End Try
    
    	Return ds
    End Function
     
    Thanks, Ed

    Microsoft MVP - ASP/ASP.NET

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 3:55 PM
    • Loading...
    • chris_koehne
    • Joined on 02-13-2007, 1:29 PM
    • Posts 59
    • Points 8

     Hi Ed,

    I get the error 'Type "DataRow" is not defined'?

    Chris 

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 4:29 PM
    • Loading...
    • limno
    • Joined on 06-10-2005, 3:50 PM
    • Iowa, USA
    • Posts 4,265
    • Points 75,892
    • Moderator
      TrustedFriends-MVPs

    Another version with SQLDataSource and dynamic generated textbox.

     

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="dynamicTextBoxVB.aspx.vb" Inherits="dynamicTextBoxVB" %>
    
    <!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">
        <div>
             <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:test_for_forumConnectionString %>"
                SelectCommand="SELECT [ID], [Name] FROM [NameForTextBox]" DataSourceMode="DataReader"></asp:SqlDataSource>
      
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:test_for_forumConnectionString %>"
                DeleteCommand="DELETE FROM [NameForTextBoxForInsert] WHERE [ID] = @ID" InsertCommand="INSERT INTO [NameForTextBoxForInsert] ([fromLabel], [fromTextBox]) VALUES (@fromLabel, @fromTextBox)"
                SelectCommand="SELECT [ID], [fromLabel], [fromTextBox] FROM [NameForTextBoxForInsert]"
                UpdateCommand="UPDATE [NameForTextBoxForInsert] SET [fromLabel] = @fromLabel, [fromTextBox] = @fromTextBox WHERE [ID] = @ID">
                <DeleteParameters>
                    <asp:Parameter Name="ID" Type="Int32" />
                </DeleteParameters>
                <UpdateParameters>
                    <asp:Parameter Name="fromLabel" Type="String" />
                    <asp:Parameter Name="fromTextBox" Type="String" />
                    <asp:Parameter Name="ID" Type="Int32" />
                </UpdateParameters>
                <InsertParameters>
                    <asp:Parameter Name="fromLabel" Type="String" />
                    <asp:Parameter Name="fromTextBox" Type="String" />
                </InsertParameters>
            </asp:SqlDataSource>
            <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
                DataSourceID="SqlDataSource2">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                        SortExpression="ID" />
                    <asp:BoundField DataField="fromLabel" HeaderText="fromLabel" SortExpression="fromLabel" />
                    <asp:BoundField DataField="fromTextBox" HeaderText="fromTextBox" SortExpression="fromTextBox" />
                </Columns>
            </asp:GridView>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Insert data from Textbox" />
        
        </div>
        </form>
    </body>
    </html>
     
    Imports System.Data.SqlClient
    Imports System.Data
    Imports System
    
    Partial Class dynamicTextBoxVB
        Inherits System.Web.UI.Page
        Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
            'generate all textbox 
    
            myfunctionAddTextBox()
            MyBase.OnInit(e)
    
        End Sub
    
        Protected Sub myfunctionAddTextBox()
            Dim ctrlTable1 As New Table()
            ctrlTable1.CellPadding = 0
            ctrlTable1.CellSpacing = 1
            ctrlTable1.Attributes.Add("Border", "1")
    
    
            Dim reader As System.Data.SqlClient.SqlDataReader = DirectCast(SqlDataSource1.[Select](DataSourceSelectArguments.Empty), System.Data.SqlClient.SqlDataReader)
    
    
            ' start 
    
            While reader.Read()
                Dim tr As New TableRow()
    
    
                Dim tc1 As New TableCell()
                Dim lbl1 As New Label()
    
                lbl1.Attributes.Add("runat", "Server")
                lbl1.EnableViewState = True
                lbl1.Width = 20
                lbl1.ID = "lbl" + reader(0).ToString()
    
                lbl1.Visible = True
                lbl1.Text = reader(1).ToString()
                '0:ID; 1:Name; 
                tc1.Controls.Add(lbl1)
                tr.Cells.Add(tc1)
    
    
                Dim tc2 As New TableCell()
                Dim tb2 As New TextBox()
    
                tb2.Attributes.Add("runat", "Server")
                ' tb2.EnableViewState = true; 
                tb2.Width = 80
                tb2.ID = "txt" + reader(0).ToString()
                'tb2.ReadOnly = true; 
                tb2.Visible = True
    
    
                tc2.Controls.Add(tb2)
                tr.Cells.Add(tc2)
    
    
                ctrlTable1.Rows.Add(tr)
            End While
    
    
            Me.Form.Controls.Add(ctrlTable1)
        End Sub
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim reader As SqlDataReader = DirectCast(SqlDataSource1.[Select](DataSourceSelectArguments.Empty), SqlDataReader)
    
            While reader.Read()
                Dim strLabel As String = ""
                Dim strTextBox As String = ""
    
                Dim myLabel As New Label()
                Dim myLabelId As String = "lbl" + reader(0).ToString()
    
                Dim txtTextBox As New TextBox()
                Dim myTxtId As String = "txt" + reader(0).ToString()
    
    
    
    
    
                txtTextBox = DirectCast(Me.FindControl(myTxtId), TextBox)
                If txtTextBox IsNot Nothing Then
    
                    strTextBox = txtTextBox.Text.ToString()
                Else
                    strTextBox = ""
                End If
    
    
                myLabel = DirectCast(Me.FindControl(myLabelId), Label)
                If myLabel IsNot Nothing Then
    
                    strLabel = myLabel.Text.ToString()
                Else
                    strLabel = ""
                End If
    
    
    
                If strLabel <> "" Then
    
    
                    SqlDataSource2.InsertParameters("fromLabel").DefaultValue = strLabel
                    SqlDataSource2.InsertParameters("fromTextBox").DefaultValue = strTextBox
                    'SqlDataSource2.InsertParameters["createdBy"].DefaultValue = User.Identity.Name; 
                    'SqlDataSource2.InsertParameters["createdDate"].DefaultValue = DateTime.Now.ToString(); 
    
    
    
                    'add data to table2 
                    SqlDataSource2.Insert()
    
    
    
                    txtTextBox.Text = ""
    
                End If
            End While
            ' Close the reader 
            reader.Close()
    
    
        End Sub
    
    End Class
     
    Tables:

    CREATE TABLE [dbo].[NameForTextBoxForInsert](

    [ID] [int] IDENTITY(1,1) NOT NULL,

    [fromLabel] [nvarchar](50) NULL,

    [fromTextBox] [nvarchar](50) NULL)

     

    CREATE TABLE [dbo].[NameForTextBox](

    [ID] [int] NULL,

    [Name] [nvarchar](50) NULL

    )

     
     
    Limno

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 4:58 PM
    • Loading...
    • chris_koehne
    • Joined on 02-13-2007, 1:29 PM
    • Posts 59
    • Points 8

     Hi,

    generating the dynamic textboxes is now working with the code of limno (thanks).

    How can I now use the different textboxes for further search - what is the ID for example for the  third TextBox if I want to use it in a later SQL Select?

    Chris
     

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 5:07 PM
    • Loading...
    • limno
    • Joined on 06-10-2005, 3:50 PM
    • Iowa, USA
    • Posts 4,265
    • Points 75,892
    • Moderator
      TrustedFriends-MVPs

    If you can save the data from textbox to your database table, you should be able to do the same to find the value from the textbox to construct your search parameter. You may need to add condtion check to choose which textbox to use in your code.

    Limno

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 6:02 PM
    • Loading...
    • chris_koehne
    • Joined on 02-13-2007, 1:29 PM
    • Posts 59
    • Points 8

     Hi,

    now it is working, thanks, but how to position the dynamic table somewhere on the page. It always appears in the bottom end...

     

    Chris 

  • Re: New empty textbox for every row in sql database?

    07-24-2008, 8:54 PM
    Answer
    • Loading...
    • limno
    • Joined on 06-10-2005, 3:50 PM
    • Iowa, USA
    • Posts 4,265
    • Points 75,892
    • Moderator
      TrustedFriends-MVPs

    You can try to use a placeholder to hold the dynamic controls or to create an asp table from your UI page instead of dynamic creation.

    Limno

Page 1 of 1 (13 items)