我是 C# 新手,这个问题一定是一个常见问题,但这确实需要我的时间。在这种情况下,我无法在我的项目中走得更远。
我需要的是,我只想通过在 button_Click 事件中调用 form1 中的方法将值从 form2 listview 传递到 form1 文本框。然而,当我单击将触发我的代码的按钮时,我什么也得不到。
遇到的问题:
1:当我声明Form1 f1 = New Form1()时,编译器仍然编译我的方法将在Form2中的Button_Click事件中调用的代码。但是当我单击按钮时,我的文本框中没有发生任何变化。
2:当我将 Form1 声明为 Public Form1 f1; 并单击按钮时,我得到了 NullReferenceException 。
3:我需要将我的 Form2 显示为 ShowDialog();
任何帮助将不胜感激。
我在 Form1 中的代码
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;
using System.Globalization;
using System.Threading;
namespace Practice_CS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnViewList_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
public void setFields(string sName,string sAge,string sGender) {
txtName.Text = sName;
txtAge.Text = sAge;
txtGender.Text = sGender;
}
}
}
我在 Form2 中的代码
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 Practice_CS
{
public partial class Form2 : System.Windows.Forms.Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
lvlist.Items.Add("Juli");
lvlist.Items[0].SubItems.Add("20");
lvlist.Items[0].SubItems.Add("Male");
lvlist.Items.Add("Mark");
lvlist.Items[1].SubItems.Add("21");
lvlist.Items[1].SubItems.Add("Male");
lvlist.Items.Add("Shiela");
lvlist.Items[2].SubItems.Add("18");
lvlist.Items[2].SubItems.Add("Female");
}
private void btnSelect_Click(object sender, EventArgs e)
{
if (lvlist.Items.Count < 1) { return; }
Form1 f1 = new Form1();
f1.setFields(lvlist.FocusedItem.Text, lvlist.FocusedItem.SubItems[1].Text, lvlist.FocusedItem.SubItems[2].Text);
this.Close();
}
private void lvlist_DoubleClick(object sender, EventArgs e)
{
btnSelect_Click(btnSelect, e);
}
}
}