简体   繁体   中英

C# - Setting a Value in a Button then passing it into a ListView

I have two forms, form1 and form2.

In form1, there is are two buttons, button1 and button2.

In form2, there is a listview, ListView1.

button1 should hold a string value called "Vanilla".

When button2 is pressed it opens form2.

On form2, in listview1 it should show "Vanilla" in the first column.

Form1

public partial class form1 : Form
{

public static string buttonValue = "";
    public form1()
    {
        InitializeComponent();
    }

    public void button1_Click(object sender, EventArgs e)
        {
            buttonValue = "Vanilla";
        }

    public void button2_Click(object sender, EventArgs e)
        {
              form2 form2 = new form2();
              form2.Show();
              this.Hide();
        }

Form2

public partial class form2 : Form
{
    public form2()
    {
        InitializeComponent();
    }

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

You can design the second form as bellow:

public partial class form2 : Form
{
    public form2()
    {
        InitializeComponent();
    }

    private string _passedValue = "";

    public form2(string passedValue)
    {
        InitializeComponent();
        _passedValue = passedValue;
        listView1.Items.Add(_passedValue);
    }

    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

You can pass the value stored in the first button using the bellow code.

public void button2_Click(object sender, EventArgs e)
{
    form2 form2 = new form2(buttonValue);
    form2.Show();
    this.Hide();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM