Reputation: 371
I am having class
MainForm.cs where its MainFormDesigner.cs
public System.Windows.Forms.Label diffTime;
I want this labels value to be assigned in Other class
Request.cs class When I try in these way
MainForm.diff.Text = "Diff:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Tried giving static in MainForm but unable to get label values assigned in other class.
How can I do this, any help on this please.
Upvotes: 1
Views: 592
Reputation: 422
A cheating
way:
public partial class MainForm : Form
{
public static System.Windows.Forms.Label diffTime;
public MainForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
diffTime = new System.Windows.Forms.Label();
diffTime.AutoSize = true;
diffTime.Location = new System.Drawing.Point(113, 55);
diffTime.Name = "diffTime";
diffTime.Size = new System.Drawing.Size(35, 13);
diffTime.TabIndex = 0;
diffTime.Text = "label1";
this.Controls.Add(diffTime);
}
then in Request.cs
you can call MainForm.diff.Text = "Diff:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
But I recommend you follow Reza Aghaei's answer, you need some variable to hold your MainForm's instance: Request.cs:
public class Request
{
public static MainForm mainForm = null;
public static void setLabelText()
{
mainForm.diffTime.Text = "Diff:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
}
Assuming MainForm
is called in Program.cs:
Request.mainForm = new MainForm(); //pass your instance to Request.cs
Application.Run(Request.mainForm);
Upvotes: 0
Reputation: 125332
Go to Designer of your form, select your label, in properties, select Modifier
then change the value of modifier to public
.
Then in other class, assuming, there you have an instance of your MainForm do this:
//if the variable of instance of your MainForm is mainForm for example:
mainForm.diff.Text = "Diff:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Upvotes: 4