Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

All.

I'm newbie in C#. I know this is very popular question. But I didn't understand. I know there is a mistake, but where? For example - first part of code Form1 include private variable test, I need to get the value of this variable in the Form2. Where is the error?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string test = "test this point";
            Form2 dlg = new Form2();
            dlg.test = test;
            dlg.Show();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public string test { get; set; }

        public Form2()
        {
            InitializeComponent();
            label1.Text = test;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
330 views
Welcome To Ask or Share your Answers For Others

1 Answer

In your Form2 you are using a public property, because it is public you can assign it via the object in form1. For example:

 private void button1_Click(object sender, EventArgs e)
        {
            Form2 dlg = new Form2();
            dlg.test = "test this point";
            dlg.Show();
        }

There are a couple of ways to use this in form 2, if you just want it to set the text property of the label only, this would be the best:

public partial class Form2 : Form
    {
        public string test 
        { 
           get { return label1.Text; }
           set { label1.Text = value ;} 
        }

        public Form2()
        {
            InitializeComponent();
        }
    }

Within the setter of the property you could also call a function if required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...