form1类是:
public partial class Form1 : Form
{
public static string passingtext;
public bool click = true;
public Form1()
{
InitializeComponent();
}
Form2 form2;
private void button1_Click(object sender, EventArgs e)
{
form2.passThisValuetoDgv(textBox1.Text, textBox2.Text); // pass this value to form2
}
private void button2_Click(object sender, EventArgs e)
{
form2 = new Form2(this);
if (click) //to avoid open a multiple form...
{
form2.Show(); //i change from form2.Showdialog() so that you can make a data entry...
click = false;
}
表格2类是:
public partial class Form2 : Form
{
private Form1 form1;
public Form2(Form1 form2)
{
InitializeComponent();
this.form1 = form2;
}
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\acE\documents\visual studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf;Integrated Security=True;User Instance=True");
DataTable dt;
public void AddGridViewRows(string id, string name)
{
dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dataGridView1.DataSource = dt;
dt.Rows.Add(id);
dataGridView1.CurrentRow.Cells[1].Value = name;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void disp_data()
{
cn.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
dataGridView1.DataSource = dt;
cn.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "id";
dataGridView1.Columns[1].Name = "name";
disp_data();
}
string[] row;
public void passThisValuetoDgv(string id, string name)
{
if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(name)) //if values are not null...
{
row = new string[] { id, name }; //new inserted row...
}
}
//handle this event so that you can still open this form after close...
public string passvalue { get; set; }
private void button1_Click(object sender, EventArgs e)
{
form1.click = true;
}
答案 0 :(得分:0)
您传递的文字已经是静态的,您只需要string text = Form1.passingtext;
您还将Form1传递给Form2,并感觉Form1中的passingtext
是静态的,您无法使用Form1的对象名称来访问它。
要修复此以太删除静态和我们form1Object.passingtext
或保持静态,不要将Form1传递到Form2并执行Form1.passingtext