C# 从asp.net中动态创建的文本框中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11992311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text from dynamically created textbox in asp.net
提问by mElling
I've been banging my head against this all morning, so hopefully I can get some help. Essentially I'm having issues getting values from some textbox controls I'm creating dynamically in .net 4.
我整个上午都在为此烦恼,所以希望我能得到一些帮助。本质上,我在从我在 .net 4 中动态创建的一些文本框控件中获取值时遇到了问题。
Here's the desired flow of the application.
这是应用程序所需的流程。
1). User selects a html document from a dropdown menu that is a template for a letter. This html document has tags of the format $VARIABLENAME$ that will be replaced with the correct values.
1)。用户从作为信件模板的下拉菜单中选择一个 html 文档。此 html 文档具有 $VARIABLENAME$ 格式的标签,这些标签将被正确的值替换。
2). The program runs though the template and pulls out all strings of the format $STRING$ and stores them in a list.
2)。该程序通过模板运行并提取格式为 $STRING$ 的所有字符串并将它们存储在列表中。
3). For each entry in this list, the program generates an asp:label and an asp:textbox with a unique ID based on the original $VARIABLENAME$ field.
3)。对于此列表中的每个条目,程序会根据原始 $VARIABLENAME$ 字段生成具有唯一 ID 的 asp:label 和 asp:textbox。
4). User enters replacement values, and hits submit.
4)。用户输入替换值,然后点击提交。
5). Program replaces all $STRING$'s with the replacement values and outputs the result.
5)。程序用替换值替换所有 $STRING$ 并输出结果。
Everything works well up to the point where I need to get values from the text boxes. I'm quite sure it's an issue with the page lifecycle, but because the textboxes are not being generated until the use selects the desired template from the dropdown, I'm not sure how to make them persist through postbacks so I can reference them.
一切正常,直到我需要从文本框中获取值为止。我很确定这是页面生命周期的问题,但是因为直到用户从下拉列表中选择所需的模板才会生成文本框,所以我不确定如何使它们通过回发保持不变,以便我可以引用它们。
Am I going about this all wrong? How do I access the text fields created from a dropdown event after a postback froma submitbutton event occurs?
我在这一切都错了吗?从提交按钮事件发生回发后,如何访问从下拉事件创建的文本字段?
EDIT: Here's the most of the relevant code.
编辑:这是大部分相关代码。
protected void createTextBoxes(List<string> results)
{
if (results != null)
{
foreach (string result in results)
{
string formattedResult = result.Substring(1, result.Length - 2);
formattedResult = formattedResult.ToLower();
formattedResult = char.ToUpper(formattedResult[0]) + formattedResult.Substring(1);
var label = new Label();
label.ID = formattedResult;
label.Text = formattedResult + ": ";
templateFormPlaceholder.Controls.Add(label);
var textBox = new TextBox();
textBox.ID = result;
templateFormPlaceholder.Controls.Add(textBox);
templateFormPlaceholder.Controls.Add(new LiteralControl("<br />"));
previewBtn.Visible = true;
}
}
}
protected void templateDD_SelectedIndexChanged(object sender, EventArgs e)
{
var templatePath = "";
if (templateDD.SelectedIndex == 0)
{
previewBtn.Visible = false;
}
if (templateDD.SelectedIndex == 1)
{
templatePath = employeePath;
}
else if (templateDD.SelectedIndex == 2)
{
templatePath = managerPath;
}
List<string> regMatches = FindMatches(templatePath);
Session["regMatches"] = regMatches;
createTextBoxes(regMatches);
}
protected void Page_Init(object sender, EventArgs e)
{
if (Session["regMatches"] != null)
{
createTextBoxes((List<string>)Session["regMatches"]);
}
}
Later on, I'm trying to add the values from these textboxes to a dictionary. Parameters is the name of the dictionary. The key field is the $STRING$, result is what the user entered in the text box.
稍后,我尝试将这些文本框中的值添加到字典中。参数是字典的名称。关键字段是 $STRING$,结果是用户在文本框中输入的内容。
protected void previewBtn_Click(object sender, EventArgs e)
{
List<string> matchResults = (List<string>)Session["regMatches"];
Dictionary<string, string> parameters = new Dictionary<string, string>();
foreach (string result in matchResults)
{
TextBox tb = (TextBox)templateFormPlaceholder.FindControl(result);
parameters.Add(result, tb.Text);
}
var template = ReplaceKeys(parameters);
outputLBL.Text = template;
Here's the .aspx code.
这是 .aspx 代码。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="offerLetter.aspx.cs" Inherits="templateRegexTesting.offerLetter" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
Which template would you like to use?
</p>
<asp:DropDownList ID="templateDD" runat="server" OnSelectedIndexChanged="templateDD_SelectedIndexChanged"
AutoPostBack="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1">Employee</asp:ListItem>
<asp:ListItem Value="2">Manager</asp:ListItem>
</asp:DropDownList>
<br />
<asp:PlaceHolder ID="templateFormPlaceholder" runat="server" />
<div>
<asp:Button ID="previewBtn" runat="server" Text="Preview" Visible="false" OnClick="previewBtn_Click" />
</div>
<div>
<asp:Label ID="outputLBL" runat="server"></asp:Label>
</div>
<br />
</div>
</form>
</body>
</html>
EDIT: I put this in a comment when I figured it out, but I figured I should move it into the question so it is more visible:
编辑:当我想出来时,我把它放在评论中,但我想我应该把它移到问题中,这样它就更明显了:
Thought I should update this. I feel like a bit of an idiot, but I did manage to get this working. Basically I was assigning the controls an ID equal to the replacement tokens (So ID="$FIRSTNAME$" for example). It didn't even dawn on me that the $'s would cause any issues. When I just changed to the format ID="Firstname" it works perfectly. Thank you for all of the help!
想我应该更新这个。我觉得自己有点白痴,但我确实设法让它发挥了作用。基本上,我为控件分配了一个等于替换标记的 ID(例如,ID="$FIRSTNAME$")。我什至没有意识到 $ 会引起任何问题。当我刚刚更改为格式 ID="Firstname" 时,它可以完美运行。谢谢大家的帮助!
采纳答案by Andre Calil
You're right, it's all about the page lifecycle. Dynamically created controls must be re-created at the Page_Initstage, in order to exist beforethe viewstate binding stage. This means that will have to somehow (using the Session, maybe) store how many textboxesyou have created on the previous processing to recreate them. Remind to use the same IDand to add them to your control tree (a repeater or something else that you're using).
你是对的,这都是关于页面生命周期的。动态创建的控件必须在Page_Init阶段重新创建,以便在视图状态绑定阶段之前存在。这意味着必须以某种方式(使用Session,也许)存储textboxes您在先前处理中创建的数量以重新创建它们。提醒使用相同的 ID并将它们添加到您的控制树(中继器或您正在使用的其他东西)。
UPDATE
更新
Let me give you a suggestion:
1. Declare a class attribute of type List<TextBox>(let's call it CreatedTextBoxes)
让我给你一个建议:1.声明一个类型的类属性List<TextBox>(我们称之为CreatedTextBoxes)
Declare a method that receives whatever it needs to create the textboxes. This method must not read anything outside of it's scope. It will simply receive some args, create the textboxes and add them to another control (such as a
Repeater). Add each textbox created toCreatedTextBoxesAt the dropdown change event, read the option, save it to the
Sessionand call this methodAt
Page_Init, verify that object at theSession. If it's null or empty, don't do anything. If it has a value, call that same method, passing the same args- When you need to retrieve that from the dynamically created textboxes, use
CreatedTextBoxesand notFindControls()
声明一个方法,该方法接收创建文本框所需的任何内容。此方法不得读取其范围之外的任何内容。它只会接收一些参数,创建文本框并将它们添加到另一个控件(例如 a
Repeater)。将创建的每个文本框添加到CreatedTextBoxes在下拉更改事件中,读取选项,将其保存到
Session并调用此方法在 处
Page_Init,在 处验证该对象Session。如果它为 null 或为空,则不要做任何事情。如果它有一个值,调用相同的方法,传递相同的参数- 当您需要从动态创建的文本框中检索它时,请使用
CreatedTextBoxes而不是FindControls()
回答by Igor
You add TextBoxcontrols to templateFormPlaceholder.Controlsbut use form1.FindControlto find them. FindControlmethod will find a control only if the control is directly contained by the specified container- from http://msdn.microsoft.com/en-us/library/486wc64h.aspx. Try calling templateFormPlaceholder.FindControlinstead.
您将TextBox控件添加到templateFormPlaceholder.Controls但用于form1.FindControl查找它们。仅当指定容器直接包含控件时,FindControl方法才会找到控件- 来自http://msdn.microsoft.com/en-us/library/486wc64h.aspx。试试打电话吧templateFormPlaceholder.FindControl。
回答by Sinoy Siby
Create Dynamic TextBoxes and add it to a asp panel so that you can access it easily.
创建动态文本框并将其添加到 asp 面板,以便您可以轻松访问它。
Here is the ASP.NET design elements.
下面是 ASP.NET 的设计元素。
<div class="form-group">
<asp:Panel ID="panel" runat="server" CssClass="form-group">
</asp:Panel>
</div>
C# Code to generate Dynamic textboxes
生成动态文本框的 C# 代码
protected void create_dynamic_text(object sender, EventArgs e)
{
int num = 5; // you can give the number here
for (int i = 0; i < num;i++ )
{
TextBox tb = new TextBox();
tb.ID = "txt_box_name" + i.ToString();
tb.CssClass = "add classes if you need";
tb.Width = 400; //Manage width and height
panel.Controls.Add(tb); //panel is my ASP.Panel object. Look above for the design code of ASP panel
}
}
C# Code to Take Values
取值的 C# 代码
protected void reade_values(object sender, EventArgs e)
{
int num=5; // your count goes here
TextBox tb = new TextBox();
for (int i = 0; i < num; i++)
{
tb=(TextBox)panel.FindControl("txt_box_name"+i.ToString());
string value = tb.Text; //You have the data now
}
}
}

