我无法访问从后面的代码创建的表格单元格内的文本框内容。在我的小程序中,该表预先填充了学生的姓名(单元格A1)。文本框将添加到其下方的单元格中(单元格A2)。用户在文本框中输入Pass或Fail,然后单击submit。此时,消息应显示为“学生状态已更改为(无论用户输入的是什么)”。这是问题 - 因为文本框ID(student1)在后面的代码中分配,文本框ID在上下文中不存在。
//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
Label nameStudent = new Label()
{
Text = "Annie McDonald"
};
TableCell nameCell = new TableCell();
nameCell.Controls.Add(nameStudent);
NameRow.Cells.Add(nameCell);
TextBox status = new TextBox()
{
ID = "student1",
Text = "Pass or Fail"
};
TableCell statusCell = new TableCell();
statusCell.Controls.Add(status);
StatusRow.Cells.Add(statusCell);
}
protected void sumbitChange_Click(object sender, EventArgs e)
{
Confirm.InnerText = "The students status was changed to " + student1.Text;
}
<body>
<form id="form1" runat="server">
<asp:Table ID="StudentRoster" runat="server">
<asp:TableRow ID="NameRow" runat="server" />
<asp:TableRow ID="StatusRow" runat="server" />
</asp:Table>
<asp:Button ID="sumbitChange" text="Submit" runat="server" OnClick="sumbitChange_Click"/>
<p id="Confirm" runat="server"></p>
</form>
</body>
答案 0 :(得分:1)
您需要在TableRow中找到TextBox。请尝试以下代码:
protected void sumbitChange_Click(object sender, EventArgs e)
{
TextBox student1 = StatusRow.FindControl("student1") as TextBox;
Confirm.InnerText = "The students status was changed to " + student1.Text;
}
我已经过测试,它正在运作。
答案 1 :(得分:0)
在我看来,你误解了ASP.NET WebForms的工作方式。您通常会在*.aspx
或*.ascx
文件中声明控件,为其分配ID并通过后面的代码(*.aspx.cs
或*.ascx.cs
)访问它们。
在你的情况下,这将是这样的:
* .aspx文件
<form id="form1" runat="server">
<p class="someFancyInformationStyle"><asp:Label ID="statusLabel" runat="server"></asp:Label></p>
<table>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
<tr>
<td><asp:Label ID="nameLabel" runat="server"></asp:Label></td>
<%-- Or even better, use a drop down --%>
<td><asp:TextBox ID="statusTextBox" runat="server"></asp:TextBox></td>
</tr>
...
</table>
</form>
代码隐藏文件:
protected void sumbitChange_Click(object sender, EventArgs e)
{
statusLabel.Text = "The students status was changed to " + statusTextBox.Text;
}