我想使用文字工具动态创建文本框,但文本框没有执行。请帮忙。
<tr>
<td><p>Number of days taken : </p></td>
<td>
<asp:TextBox ID="txtLeaveTakenDays" Width="210" runat="server"></asp:TextBox>
</td>
<td><asp:Button ID="DayButton" runat="server" Text="Enter Date"
onclick="DayButton_Click" />
</td>
</tr>
在DayButton点击事件中,这里是aspx.cs代码
int DaysEnter = Convert.ToInt32(txtLeaveTakenDays.Text);
StringBuilder put;
put = new StringBuilder();
for (int i = 0; i < DaysEnter; i++)
{
put.Append("<tr><td style=\"text-align:right;\"><p>Day " + (i+1) + " : </p></td><td><asp:TextBox ID=\"DayDateDay" + (i+1) + "\" Width=\"210\" runat=\"server\" style=\"text-align:center;\"></asp:TextBox></td></tr>");
}
DayDateLiteral.Text = put.ToString();
答案 0 :(得分:0)
它不起作用的原因是因为您无法从文字控件中的字符串创建控件。有几种方法可以达到你想要的效果。
如果您不需要附加到生成的文本框的服务器端功能,那么您可以通过jQuery完成所有操作。
e.g。
<tr>
<td><p>Number of days taken : </p></td>
<td>
<asp:TextBox ID="txtLeaveTakenDays" ClientIDMode="Static" Width="210" runat="server" />
</td>
<td>
<asp:Button ID="DayButton" runat="server" Text="Enter Date" onclientclick="addTR()" />
</td>
</tr>
<script>
function addTR() {
var days = $('#txtLeaveTakenDays').text();
$('tr:last-of-type').append("<tr><td style='text-align:right;''><p>Day " + days + " : </p></td><td><input type='text' id='DayDateDay" + days + "' style='text-align:center;' width='210' text='" + days + "' /></td></tr>);
}
</script>
如果要以编程方式添加服务器控件,则需要首先在代码隐藏中创建控件,然后将其添加到页面上已有的另一个服务器控件 - 下面的示例添加一个表标记并使其成为服务器端控制。
HTML
<table id="DayTable" runat="server">
<tr>
<td>
<p>Number of days taken : </p></td>
<td>
<asp:TextBox ID="txtLeaveTakenDays" ClientIDMode="Static" Width="210" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="DayButton" runat="server" Text="Enter Date" onclick="DayButton_Click" />
</td>
</tr>
</table>
VB
Protected Sub DayButton_Click(sender As Object, e As EventArgs)
Dim TR As New HtmlTableRow
Dim TD1 As New HtmlTableCell
TD1.Attributes.Add("style", "text-align:right;")
TD1.InnerHtml = "<p>Day " & txtLeaveTakenDays.Text & " : </p>"
Dim TD2 As New HtmlTableCell
Dim TB As New TextBox
TB.ID = "DayDateDay" & txtLeaveTakenDays.Text
TB.Attributes.Add("style", "text-align:center;")
TB.Width = 210
TB.Text = txtLeaveTakenDays.Text
TD2.Controls.Add(TB)
TR.Controls.Add(TD1)
TR.Controls.Add(TD2)
DayTable.Controls.Add(TR)
End Sub
C#
protected void DayButton_Click(object sender, EventArgs e)
{
HtmlTableRow TR = new HtmlTableRow;
HtmlTableCell TD1 = new HtmlTableCell;
TD1.Attributes.Add("style", "text-align:right;");
TD1.InnerHtml = "<p>Day " + txtLeaveTakenDays.Text + " : </p>";
HtmlTableCell TD2 = new HtmlTableCell;
TextBox TB = new TextBox;
TB.ID = "DayDateDay" + txtLeaveTakenDays.Text;
TB.Attributes.Add("style", "text-align:center;");
TB.Width = 210;
TB.Text = txtLeaveTakenDays.Text;
TD2.Controls.Add(TB);
TR.Controls.Add(TD1);
TR.Controls.Add(TD2);
DayTable.Controls.Add(TR);
}
VB / C#代码创建每个td,文本框和新tr作为控件,然后将它们添加到表中。这样,您就可以从后面的代码中访问生成的文本框。
答案 1 :(得分:-1)
您可以使用PlaceHolderControl
向页面添加动态控件。有关如何操作的示例,请参阅此link。