user10083973
user10083973

Reputation:

Display label from one form to another form

I have one form in my software that is displaying the total value (it is a label), and I want to display the value of that label on another form.

Here is my code:

public void PresmetajTotal()
{   
    for (var i = 0; i < dataGridView1.Rows.Count; i++)
    {
        vkp += Convert.ToInt64(dataGridView1.Rows[i].Cells[4].Value);

         lblTotal.Text = vkp.ToString();
    }
}

And on the other form I created this:

 private void Change_Load(object sender, EventArgs e)
 {
     Prodazba prodaz = new Prodazba();
     label4.Text = prodaz.lblTotal.Text();
 }

The error i get is : CS0122 'Prodazba.lblTotal' is inaccessible due to its protection level

Upvotes: 0

Views: 53

Answers (2)

Ophaedean Rhythm
Ophaedean Rhythm

Reputation: 103

Tw things:

  1. You are creating an new form with new Prodazba()
  2. Your label is private

The second one is easier to deal with. In the form editor, or your designer code, set the access level to internal or public.

For the first one, you could take several approaches depending on how the forms are created. If your first form loads the Prodazba, you could:

public partial class YourMainForm
{
    Prodazba prodaz;

then...

private void Change_Load(object sender, EventArgs e)
{
    prodaz = new Prodazba();
    prodaz.Load += delegate {this.label4.Text = prodaz.Total};
    prodaz.Show();
}

If your label is internally accessable, you could run any event handler from it, like prodaz.label4.TextChanged += ...

Upvotes: 0

Daniel Loudon
Daniel Loudon

Reputation: 799

Add a public property in Prodazba form that will return the value of the label.

public partial class Prodazba()
{
    public string Total { get { return lblTotal.Text; } }

    //....
}

Then access it like:

private void Change_Load(object sender, EventArgs e)
{
    Prodazba prodaz = new Prodazba();
    label4.Text = prodaz.Total;
}

Upvotes: 1

Related Questions