简体   繁体   English

保存动态创建的文本框的值

[英]Save the value of Dynamically created textbox

UPDATE1: I am Investigating this link. UPDATE1:我正在研究此链接。 Retaining dynamically created controls during PostBack - VB.net It may explained what I need to know. 在PostBack期间保留动态创建的控件-VB.net它可以解释我需要知道的内容。 The comment in above link mentioned to recreate the control using the same ID. 上面链接中的注释提到使用相同的ID重新创建控件。 ASP.net will automatically retain the value. ASP.net将自动保留该值。 I will then be able to find the control and get the typed value. 然后,我将能够找到控件并获得键入的值。 .. thanks .. .. 谢谢 ..

UPDATE2: Thanks to Win's comment bellow and a link above, I think I figure this out. UPDATE2:感谢Win的注释和下面的链接,我想我可以解决这个问题。 Will confirm and post answer later. 稍后将确认并发布答案。

I must apologize it seems like there is a thousand of similar question to this. 我必须道歉,好像有成千上万的类似问题。 But after reading many question and answer I still cannot seem to make my simple page working. 但是,在阅读了许多问答之后,我似乎仍然无法使我的简单页面正常工作。 I am very new at this. 我对此很陌生。 Please allow me to ask this again. 请允许我再问一次。

I have this very simple ASPX page with one dropdown, a table and one button. 我有一个非常简单的ASPX页面,其中包含一个下拉列表,一个表格和一个按钮。 The drop down is populated using datatable (datatable is from SQL table). 使用数据表填充下拉列表(数据表来自SQL表)。 the table is used for a container of a dynamically created textbox. 该表用于动态创建的文本框的容器。 and a button to do the updating. 和一个按钮进行更新。 below is my code snippet for the ASPX and vb.net code behind 以下是我背后的ASPX和vb.net代码的代码段

The problem that I am facing is that the page.findcontrol is unable to locate the control that was dynamically created. 我面临的问题是page.findcontrol无法找到动态创建的控件。 I vaguely understand that is a problem due to post back, page_load vs page_init. 我模糊地理解这是由于回发page_load与page_init而引起的问题。 but I still don't have full understanding after all the tutorials I read :( .. could you please help how to make this work? 但是在我阅读了所有教程之后,我仍然没有完全理解:( ..您能帮忙如何完成这项工作吗?

thank you so much 非常感谢

Extra info: I tried to do what is suggested in the coment anyway, and I recreate the control on page load or init, but what value would be in the textbox when I re create it? 额外信息:无论如何,我还是尝试执行建议中的建议,并在页面加载或初始化时重新创建了控件,但是当我重新创建该控件时,它在文本框中会有什么值? here is the flow as what the user see. 这是用户看到的流程。

  1. step0 The first time the page load, no dynamic textbox yet step0首次加载页面时,尚无动态文本框
  2. Step1 the user select value 34 步骤1用户选择值34
  3. step2 autopostback selectedindexchanged fired and value 34 passed back to the server and return 2 names joe and jack, it create dynamic textbox_1 with joe and dynamic textbox_2 with jack. step2 autopostback selectedindexchanged被触发,并将值34传递回服务器并返回2个名称joe和jack,它将创建带有joe的动态textbox_1和带有jack的动态textbox_2。
  4. Step3 the user typed the value jane in textbox_1. 步骤3用户在textbox_1中键入值jane。 and click button1. 然后单击button1。
  5. Step4 button1 click event fired and I am trying to capture the word jane in textbox_1 but I cannot. Step4 button1单击事件被触发,我试图在textbox_1中捕获单词jane,但我不能。 because I can't find the control of textbox_1 due to timing or my limited knowledge. 因为时间或我的知识有限,我无法找到textbox_1的控件。 this is s where I need some help. 这是我需要帮助的地方。

ASPX ASPX

<body>
    <form id="form1" runat="server">
    <div>

        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        </asp:DropDownList>
        <br />
        <br />
        <asp:Table ID="Table1" runat="server">
        </asp:Table>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />

    </div>
    </form>
</body>

VB.net VB.net

Imports System.Data.SqlClient
Public Class DynamicControl
    Inherits System.Web.UI.Page
    Dim connString As String = "Server=Local;Database=SampleData;Trusted_Connection=True;Max Pool Size=1000"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            getData()
        End If
    End Sub
    Private Sub getData()
        Dim dt As New DataTable
        Dim SQLString As String
        Dim conn As New SqlConnection
        conn.ConnectionString = connString
        conn.Open()
        SQLString = "select DepartmentID from Employee where departmentid is not null group by departmentid"
        getDataBySQLConn(SQLString, dt, conn)
        DropDownList1.DataSource = dt
        DropDownList1.DataValueField = "DepartmentID"
        DropDownList1.DataTextField = "DepartmentID"
        DropDownList1.DataBind()
    End Sub
    Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
        Dim dt As New DataTable
        Dim SQLString As String
        Dim conn As New SqlConnection
        conn.ConnectionString = connString
        conn.Open()
        SQLString = "select employeeid,lastname from Employee where departmentid =" & DropDownList1.SelectedValue.ToString
        getDataBySQLConn(SQLString, dt, conn)
        For Each rows As DataRow In dt.Rows
            Dim tTextBox As New TextBox
            Dim tr As New TableRow
            Dim tc As New TableCell
            tTextBox.ID = "txtEmployee_" & rows("EmployeeID")
            tTextBox.Text = rows("lastname")
            tr.Cells.Add(tc)
            tc.Controls.Add(tTextBox)
            Table1.Rows.Add(tr)
        Next
    End Sub
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'Update Employee set lastname = '' where employeeID = 2
        Dim iEmployeeID As Integer
        Dim sLastName As String
        Dim tTextBox As TextBox
        iEmployeeID = DirectCast(Page.FindControl("txtEmployee_1"), TextBox).ToString
        tTextBox = Page.FindControl("txtEmployee_1")
        sLastName = tTextBox.Text
    End Sub
End Class

Note: the button1 click event is not complete. 注意:button1单击事件尚未完成。 but once I can figure out how to capture the data being typed in the textbox I will be able to get the rest done. 但是一旦我弄清楚了如何捕获文本框中键入的数据,我就可以完成其余工作。 My main problem is I am unable to get the value of the txtEmployee_1 nor can I locate the controls. 我的主要问题是我无法获取txtEmployee_1的值,也无法找到控件。 I seem to have used findcontrol at the wrong time , or initialized the control at the wrong time. 我似乎在错误的时间使用了findcontrol,或者在错误的时间初始化了控件。

And this is my table 这是我的桌子

╔════════════╦══════════════╦════════════╗
║  LastName  ║ DepartmentID ║ EmployeeID ║
╠════════════╬══════════════╬════════════╣
║ Rafferty   ║           31 ║          1 ║
║ Jones      ║           33 ║          2 ║
║ Heisenberg ║           33 ║          3 ║
║ Robinson   ║           34 ║          4 ║
║ Smith      ║           34 ║          5 ║
╚════════════╩══════════════╩════════════╝

I'm doing something similar in an application I am working on. 我正在我正在处理的应用程序中执行类似的操作。 Let me give you a very simple example that I think will help: 让我给你一个非常简单的例子,我认为这会有所帮助:

Default.aspx: Default.aspx的:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication3._Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Make textbox" />
        <asp:Button ID="Button2" runat="server" Text="Get textbox text" />
    </div>
    </form>
</body>
</html>

Default.aspx.vb: Default.aspx.vb:

Public Class _Default
    Inherits System.Web.UI.Page

    Protected controlBag As New Dictionary(Of String, Control)
    Protected Const textBox1Name As String = "textBox1"
    Protected Const textBox1EnabledName As String = "textBox1Status"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If ViewState(textBox1EnabledName) = True Then
            makeTextBox()
        End If
    End Sub

    Private Sub makeTextBox()
        Dim x As New TextBox
        x.ID = textBox1Name
        If Not controlBag.ContainsKey(textBox1Name) Then
            form1.Controls.Add(x)
            controlBag.Add(x.ID, x)
        End If
    End Sub

    Private Sub removeTextBox()
        If controlBag.ContainsKey(textBox1Name) Then
            form1.Controls.Remove(controlBag(textBox1Name))
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ViewState(textBox1EnabledName) = True
        makeTextBox()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim x As New Literal

        If controlBag.ContainsKey(textBox1Name) Then
            x.Text = String.Format("Here's the text: {0}", DirectCast(controlBag(textBox1Name), TextBox).Text)
            removeTextBox()

            ViewState(textBox1EnabledName) = False
        Else
            x.Text = "The textbox does not exist"
        End If

        form1.Controls.Add(x)
    End Sub
End Class

General idea: 大概的概念:

  1. Build dynamic controls. 建立动态控件。 Add them to the page, but also add them to a dictionary. 将它们添加到页面,也将它们添加到字典。 I use Dictionary(Of String, Control). 我使用Dictionary(Of String,Control)。 This facilitates lookup of their data later. 这便于以后查找其数据。 You'll need to add logic on when to create controls and what to bind them to. 您需要添加有关何时创建控件以及将控件绑定到什么的逻辑。
  2. On postback, you must recreate the exact same controls, even if you don't want them on the final page output. 在回发时,即使您不希望它们出现在最终页面输出中,也必须重新创建完全相同的控件。 You must do this before accessing their data. 您必须先执行此操作,然后再访问其数据。 Add them to the page control collection and don't forget to add them to your dictionary. 将它们添加到页面控件集合中,不要忘记将它们添加到字典中。
  3. Use your dictionary and the name of the control id to look it up and DirectCast it to your desired control type. 使用您的字典和控件ID的名称进行查找,并将其DirectCast转换为所需的控件类型。
  4. Do whatever you needed to do with the data from the controls. 对控件中的数据进行任何所需的处理。 You mentioned textboxes, so you would use the .Text property of your casted control. 您提到了文本框,因此您将使用投射控件的.Text属性。
  5. If you are done with the control, you can remove it from the page control collection. 如果完成了该控件,则可以将其从页面控件集合中删除。 Update whatever logic you used to not create the textbox again. 更新您用来不再创建文本框的任何逻辑。

I solved this by using 我通过使用解决了这个问题

For Each s As String In Request.Params

Instead of 代替

DirectCast(Page.FindControl("txtEmployee_1"), TextBox).ToString

Using Request.Params I am able to capture what the user typed as folows 使用Request.Params,我可以捕获用户键入的内容

For Each s As String In Request.Params
  If s.contains(txtEmployee_1) THEN txtUserTyped = Request(s)
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM