Raghav
Raghav

Reputation: 11

change label text in usercontrol at run time

hello i m new to c# and im working on a project,in which i made a usercontrol1 as *label textbox datepicker*now i wnt to change the label text,i m trying this code but it is not working

using System;
using System.Windows.Forms;

namespace library_system
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

       // private string DateLabel

        public string DateLabel
        {
            **get { return DateLabel.Text; }//error when i write dateLabel.Text
            set
            {
                DateLabel.Text= value;//error datelabel.Text
            }**
        }

i m using this code in usercontrol for is it right to do this way??

and in the main form i m writing code as userControl11.DateLabel="From Date";//on for load event??Is this Right Thanks in advance!!

Upvotes: 0

Views: 10816

Answers (3)

Marco
Marco

Reputation: 57573

You are writing a property and setting itself.
If your label name is lbl you could simply use lbl.Text="what you want";
If you need a property to have a stronger check on text, you could write:

public string DateLabel
{
    get { return lbl.Text; }
    set { lbl.Text = value; }
}

So in main form you could write (suppose you have a control named uc)

uc.DateLabel = "hello";

EDITED
To be clear: suppose you have

  • one label named lbl in your UserControl1 user control
  • a UserControl1 control in your main form named uc

In your user control code you can write:

public string DateLabel
{
    get { return lbl.Text; }
    set { lbl.Text = value; }
}

In your main form you can then write:

uc.DateLabel = "what you want";

Upvotes: 4

Jethro
Jethro

Reputation: 5916

Your Property is Called DateLabel, and you are trying to set it. That doesnt make sense.

Try the following. You will need to drag a asp:Label onto you usercontrol and call it lblDateLabel.

public string DateLabel
{
    get { return lblDateLabel.Text; }
    set { lblDateLabel.Text= value; }
}

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38200

Try changing it to this (controlname is id you have given to your label)

public string DateLabel
        {
            get { return controlname.Text; }
            set
            {
                controlname.Text= value;
            }
        }

Upvotes: 2

Related Questions