我知道有很多关于此的问题,以及很多答案......但我仍然在尝试做这项工作。
OhMyVisitorsMW是我的Form1,FormAddWebsite是我的Form2。
以下是我的Form1的代码:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class OhMyVisitorsMW : Form
{
private int nbroflinksadded = -1;
FormAddWebsite FormAddWebsite = new FormAddWebsite();
public OhMyVisitorsMW()
{
InitializeComponent();
}
private void OHMyVisitorsMW_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Add(1);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
if (e.RowIndex == nbroflinksadded+1)
{
FormAddWebsite.ShowDialog();
}
else
{
contextMenuStrip2.Show(MousePosition.X, MousePosition.Y);
}
}
}
public void AddSite(string nomsite, string urlsite)
{
dataGridView1.Rows.Add(nomsite, urlsite);
dataGridView1.Update();
dataGridView1.Refresh();
}
}
}
这是我的Form2的代码:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class FormAddWebsite : Form
{
public static string nomsite;
public static string urlsite;
public FormAddWebsite()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OhMyVisitorsMW MainForm = new OhMyVisitorsMW();
nomsite = textBox1.Text;
urlsite = textBox2.Text;
MainForm.AddSite(nomsite, urlsite);
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
有什么问题? 谢谢你的帮助。
答案 0 :(得分:1)
每次点击按钮,您都会将网站详细信息添加到OhMyVisitorsMW
的新实例。
OhMyVisitorsMW MainForm = new OhMyVisitorsMW();
nomsite = textBox1.Text;
urlsite = textBox2.Text;
MainForm.AddSite(nomsite, urlsite);
您已将数据返回到显示FormAddWebsite.ShowDialog();
的实例。这可以通过多种方式实现。
在显示对话框之前和button_click处理程序
中设置FormAddWebsite.Parent = this
OhMyVisitorsMW MainForm = Parent as OhMyVisitorsMW();
或者在FormAddWebsite
中添加公共属性以获取输入的数据,并在AddSite
之后使用这些公共属性中的数据调用FormAddWebsite.ShowDialog();
。
答案 1 :(得分:1)
我更喜欢使用事件处理程序来做这样的事情。阅读以下示例。这不是一个真实的形式。我刚刚创建了示例类来演示。
public class ParentForm : Form
{
Button openButton = new Button();
public ParentForm()
{
openButton.Click += openButton_Click;
}
void openButton_Click(object sender, EventArgs e)
{
ChildForm childForm = new ChildForm();
childForm.OKButtonClick += childForm_OKButtonClick;
childForm.ShowDialog();
}
void childForm_OKButtonClick(object sender, MyEventArgs e)
{
// Use properties from event args and set data in this form
}
}
public class ChildForm : Form
{
Button okButton = new Button();
TextBox name = new TextBox();
TextBox address = new TextBox();
public event EventHandler<MyEventArgs> OKButtonClick;
public ChildForm()
{
okButton.Click += okButton_Click;
}
void okButton_Click(object sender, EventArgs e)
{
if (OKButtonClick != null)
{
MyEventArgs myEventArgs = new MyEventArgs();
myEventArgs.Name = name.Text;
myEventArgs.Address = address.Text;
OKButtonClick(sender, myEventArgs);
}
}
}
public class MyEventArgs : EventArgs
{
public string Name
{
get;
set;
}
public string Address
{
get;
set;
}
}