Reputation: 951
I have an .aspx page which creates a column of check boxes within a table using the ID to name it as such
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="testCheck" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
Later in the C# portion of the code I am attempting to retrieve the value of the check box by using the following code
CheckBox chk = (CheckBox)gridRow.FindControl("testCheck");
Ideally I would like to remove the two string and hold the value in a common constant, is there any way to do this?
Upvotes: 9
Views: 2929
Reputation: 14781
If I got it right, a static string
variable will do the job..
public static string testCheck = "testCheck";
CheckBox chk = (CheckBox)gridRow.FindControl(testCheck);
<asp:CheckBox ID="<%# ClassName.testCheck %>" runat="server"
AutoPostBack="true" />
Upvotes: 0
Reputation: 161831
Sorry, no, there's no way to do exactly what you want. You'll still wind up with two occurrences of the string:
<asp:CheckBox ID="testCheck" runat="server" AutoPostBack="true" />
and
public const string TestCheckName = "testCheck";
later
CheckBox chk = (CheckBox)gridRow.FindControl(TestCheckName );
Note that the problem isn't so much constants, as the ASP.NET markup syntax. You could do something like this:
<asp:CheckBox ID="<%= TestCheckName %>" runat="server" AutoPostBack="true" />
but that seems a little silly.
Ok, this doesn't work at all, and here's why:
In the declaration of the CheckBox, testCheck
isn't just a string. If it were a string, then the <%# %>
syntax for databinding would work. The property would be set to that string value during the DataBinding
event.
However, the ID
property isn't just a string property - it's what the designer and page parser will use to create a field with that name. Therefore, it must be set to a constant value.
The analogy would be having code like this:
protected CheckBox testCheck;
You can't use a string expression to create the name of a class member.
Upvotes: 2