Convert string to a control

  • Thread starter Thread starter Sue
  • Start date Start date
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..
 
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) {....}
}
}
 
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;
}
 
Back
Top