简体   繁体   English

C#-在按钮中设置值,然后将其传递到ListView

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

I have two forms, form1 and form2. 我有两种形式,form1和form2。

In form1, there is are two buttons, button1 and button2. 在form1中,有两个按钮,button1和button2。

In form2, there is a listview, ListView1. 在form2中,有一个列表视图ListView1。

button1 should hold a string value called "Vanilla". button1应该包含一个名为“ Vanilla”的字符串值。

When button2 is pressed it opens form2. 当按下button2时,将打开form2。

On form2, in listview1 it should show "Vanilla" in the first column. 在form2的listview1中,它应该在第一列中显示“ Vanilla”。

Form1 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 窗体2

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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