Convert string to a control

S

Sue

All

I have a bunch of label controls on my form. All those label controls
will start with the id "lblEffDt_".
(lblEffDateValue_ddlDeliveryMethod, lblEffDateValue_txtPriority
etc...)

I want to have a common function, which receives the id of the
control as a string (which would be the string after the _ underscore
in the lblEffDate) along with actual value and based on it set some
value.

private void EnableChangedControls(string controlName, string effDate)
{
((Label)("lblEffDateValue_" + controlName)).Text = effDate;
}

and I can call that fucntion as

EnableChangedControls("ddlDeliveryMethod", "01/01/07");

But it erros out with the message

"Cannot convert type 'string' to 'System.Web.UI.WebControls.Label'

Is there an easier way to do this. I have whole lot of controls on the
webform and doing something similar will help.

thanks
sue..
 
A

AlexS

You can do this with reflection. See PropertyInfo.SetValue method and
related samples in VS help or in MSDN

Or you can enumerate Controls collection of the form - unchecked code:

foreach (Control c in form.Controls) {
if (c is Label) {
if (c.Name == yourName) {....}
}
}
 
S

Sue

You can do this with reflection. See PropertyInfo.SetValue method and
related samples in VS help or in MSDN

Or you can enumerate Controls collection of the form - unchecked code:

foreach (Control c in form.Controls) {
if (c is Label) {
if (c.Name == yourName) {....}
}

}














- Show quoted text -

All

I found an easier solution.

<form id="form1" runat="server">
<asp:Label runat="server" id="lblText"> </asp:Label>
</form>

protected void Page_Load(object sender, EventArgs e)
{
EnableChangedControls("Text", "1/1/2006");
}

private void EnableChangedControls(string controlName, string
effDate)
{
Label lbl = (Label)FindControl("lbl" + controlName);
lbl.Text = effDate;
lbl.Visible = true;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top