I am trying to access values of label
and textbox
inside DataList
Using Findcontrol
. On running the program I am getting correct value of label
but no value from textbox
control. Here is the code
.aspx code
<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 code
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();
}
This code works for me, maybe you missed the 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/>");
}
}