using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stack1
{
/// <summary>
/// These references are now can be accessed any where within the solution.
/// </summary>
public class clsGlobal
{
public static Form1 frm1;
public static Form2 frm2;
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Use the global reference for form1
clsGlobal.frm1 = new Form1();
Application.Run(clsGlobal.frm1);
}
}
然后设计Form1和Form2 . 在Form1中,将所有TextBox的所有修饰符设置为Private to Public,以使其可供其他类访问(此处为Form2) . 为此,请转到TextBox的Properties,然后将Modifiers属性的值更改为Public
public Form2()
{
InitializeComponent();
//You may don't need to do this part. You may can fetch the data from the database
/////////////////////// To Disaplay Data On the DataGrid /////////////////
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Phone");
dt.Columns.Add("Country");
dt.Rows.Add("Supun", "+940711288825", "Sri Lanka");
dt.Rows.Add("Nimantha", "+940783193677", "Sri Lanka");
dataGridView1.DataSource = dt;
////////////////////////////////////////////////////////////////////////
// To avoid select multiple rows at once
dataGridView1.MultiSelect = false;
}
完成Form2的“RowHeaderMouseDoubleClick”事件
private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
//We know surely if this event fired there will be one selected row for sure
//It is in the 0th index in the collection of SelectedRows
//To access these textbox controls of form 1 inside form 2 you have to set
//their Modifiers to Public
// We use the same instance of the form1 which is already opened
clsGlobal.frm1.txtName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
clsGlobal.frm1.txtPhone.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
clsGlobal.frm1.txtCountry.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
//clsoe the Form2
this.Close();
}
在Form1中单击相应按钮的事件(In Demo btnOpenGridForm),执行以下操作
private void btnOpenGridForm_Click(object sender, EventArgs e)
{
//Use global reference for Form2
clsGlobal.frm2 = new Form2();
//You can't access Form1 now. if you want use .Show() instead of .ShowDialog()
clsGlobal.frm2.ShowDialog();
}
1 回答
请按照以下步骤操作 .