CS0120,尝试通过RadioButton将数据发送到ListBox



我在尝试编写这段代码时遇到了一些问题,我正试图用我制作的自定义对话框为访问者注册设置一个程序,它有4个单选按钮,我现在无法修复它。下面是一些表格参考的屏幕截图。https://i.stack.imgur.com/rHLcC.jpg

我的Form1代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2021415_20T1_L5IS_PP1_Assessment_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please enter your name");
}
if (textBox2.Text == "")
{
MessageBox.Show("Please enter your surname");
}
if (textBox3.Text == "")
{
MessageBox.Show("Please enter your mobile number");
}
if (textBox4.Text == "")
{
MessageBox.Show("Please enter your email");
}
if (numericUpDown1.Text == "0")
{
MessageBox.Show("Please enter the time");
}
if (numericUpDown2.Text == "0")
{
MessageBox.Show("Please enter the time");
}


else
listBox1.Items.Add(comboBox1.SelectedItem + " - John Doe" + " at " + numericUpDown1.Text + ":" + numericUpDown2.Text);
}

那么我的Form2代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2021415_20T1_L5IS_PP1_Assessment_2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
Form1.listBox1.Items.Add("");
}
}
}
}

Forms是类,它们需要相互调用方法或访问彼此的属性以在它们之间传递数据。他们还需要能够访问彼此的对象。

在您的代码中,Form1创建Form2的对象并将其作为对话框打开,但Form2不知道打开对话框的Form1的当前实例。所以你需要先解决这个问题。

您可以通过在Form2中使用一个构造函数来实现这一点,该构造函数将Form1的对象作为参数。

public partial class Form2 : Form
{
private readonly Form1 form1;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
}
//
// Rest of the code of Form2...
//
}

这里Form2知道Form1的实例,它打开了Form2作为对话框。现在点击确定按钮Form2应该可以将单选按钮的数据传递给Form2。

为此,Form1可以有一个方法,将数据作为字符串接受,并将其添加到其列表框中。

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void AddItem(string item)
{
listBox1.Items.Add(item);
}
//
// Rest of the code of Form1...
//
}

现在Form2可以在单击"确定"按钮时调用此方法。

public partial class Form2 : Form
{
private readonly Form1 form1;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
}
//
// Rest of the code of Form2...
//
private void button2_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
this.form1.AddItem("");
}
}
}

最新更新