未从数据列表的 findcontrol 获取文本框的正确值
Not getting correct value of textbox from findcontrol from datalist
我正在尝试使用 Findcontrol
访问 DataList
中 label
和 textbox
的值。在 运行 程序中,我得到 label
的正确值,但没有来自 textbox
控件的值。这是代码
.aspx代码
<asp:DataList ID="SubjectAdded" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="SubjectLbl" runat="server" Text='<%# Eval("subject") %>'</asp:Label>
</td>
<td>
<asp:TextBox ID="FeeBox" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
.aspx.cs代码
for(int i=0; i<SubjectAdded.Items.Count; i++)
{
string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text ;
string str = "UPDATE table name SET FEE='" + feeTB + "' WHERE TUTOR = '" + id+ "' AND SUBJECT = '" + subjectNameLb + "'";
SqlCommand strCmd = new SqlCommand(str, con);
con.Open();
strCmd.ExecuteNonQuery();
con.Close();
}
这段代码对我有用,也许你错过了 IsPostback
?:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SubjectAdded.DataSource = new[] {
new {Id= 1, Subject = "Text 1" },
new {Id= 2, Subject = "Text 2" },
};
SubjectAdded.DataBind();
}
}
public void Page_PreRender(object sender, EventArgs e)
{
for (int i = 0; i < SubjectAdded.Items.Count; i++)
{
string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text;
Response.Write($"{subjectNameLb}: {feeTB}<br/>");
}
}
我正在尝试使用 Findcontrol
访问 DataList
中 label
和 textbox
的值。在 运行 程序中,我得到 label
的正确值,但没有来自 textbox
控件的值。这是代码
.aspx代码
<asp:DataList ID="SubjectAdded" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="SubjectLbl" runat="server" Text='<%# Eval("subject") %>'</asp:Label>
</td>
<td>
<asp:TextBox ID="FeeBox" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
.aspx.cs代码
for(int i=0; i<SubjectAdded.Items.Count; i++)
{
string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text ;
string str = "UPDATE table name SET FEE='" + feeTB + "' WHERE TUTOR = '" + id+ "' AND SUBJECT = '" + subjectNameLb + "'";
SqlCommand strCmd = new SqlCommand(str, con);
con.Open();
strCmd.ExecuteNonQuery();
con.Close();
}
这段代码对我有用,也许你错过了 IsPostback
?:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SubjectAdded.DataSource = new[] {
new {Id= 1, Subject = "Text 1" },
new {Id= 2, Subject = "Text 2" },
};
SubjectAdded.DataBind();
}
}
public void Page_PreRender(object sender, EventArgs e)
{
for (int i = 0; i < SubjectAdded.Items.Count; i++)
{
string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text;
Response.Write($"{subjectNameLb}: {feeTB}<br/>");
}
}