Reputation: 17
I have a <label>
that does not have an id
attribute. It only has a for
attribute. Can I get the value of this label in CodeBehind C#?
This application is built in ASP.NET.
<label for="txtEmpCd">Department</label>
<asp:DropDownList ID="DropDownList4" runat="server" CssClass="form-control"></asp:DropDownList>
Upvotes: 1
Views: 1774
Reputation: 721
You cannot access from codebehind without having runat="server".
If you only can access from codebehind, find read all html literals in entire page, get element having for attribute is "txtEmpCd" which is very tedious and not the right way to do so.
In jQuery (client side), you can find label which has for attribute is "txtEmpCd" also tedious as well.
My suggestion! Why don't you add ID="txtEmpCd" to your label?
Upvotes: 0
Reputation: 360
You can access a <asp:Label>
without an ID, but it will require recursively searching through the controls on the page. This will require the label to be in the form:
<asp:Label AssociatedControlID="txtEmpCd" runat="server" />
You will need to define a recursive function as such:
private void LoopThroughLabels(Control parent)
{
foreach (Control c in parent.Controls)
{
Label label = c as Label;
if (label != null)
{
if (label.AssociatedControlID == "txtEmpCd")
{
// This is your label
}
}
if (c.HasControls())
{
LoopThroughLabels(c);
}
}
}
And for the first call, pass in the Page
:
LoopThroughLabels(Page);
Upvotes: 1
Reputation: 35514
Use a Label
with an AssociatedControlID
<asp:Label ID="Label1" runat="server" Text="Department" AssociatedControlID="DropDownList4"></asp:Label>
Upvotes: 0