[英]how to pass a values from one form to another form without creating new instance of a form in c#?
嗯,我非常清楚,調用另一種形式是很常見的要求
Form3 f3 = new Form3();
f3.ShowDialog();
但是我面臨的困難是我不想每次都創建一個新的form3實例,而且我甚至無法在向其傳遞一些參數時全局創建構造函數。
我的要求是應將form1文本框值傳遞給form3 datagrid 。
怎么做?
我的form1代碼是
String l=null;
String m= null;
Decimal n=0;
String o=null;
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
this.Cursor = Cursors.Default;
Class1 a = new Class1(mold, mcur, mshape, mwidth, mcolor);
ds.Add(a);
int c = (mold.X > mcur.X ? mcur.X : mold.X);
int b = (mold.Y > mcur.Y ? mcur.Y : mold.Y);
int w = Math.Abs(mold.X - mcur.X);
int h = Math.Abs(mold.Y - mcur.Y);
String line = LayerName.Text + "\t" + Material.Text+ "\t" + w.ToString() + "\t" + h.ToString() + "\t" + c.ToString() + "\t" + b.ToString() + "\t" + numericUpDown1.Value + "\t" + comboBox3.Text + Environment.NewLine;
l=LayerName.Text;
m=Material.Text;
n=numericUpDown1.Value;
o=comboBox3.Text;
Form3 f3 = new Form3(l, m, n, o);
f3.ShowDialog();
string path = @"C:\Users\pri\Desktop\efg.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(line);
tsw.Close();
}
else if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine(line);
tw.Close();
}
}
形式3:
public Form3(string myString, string rek, decimal myvalue, string text1)
{
InitializeComponent();
string[] Rows = new string[2];
for (int i = 0; i < Rows.Length; i++)
{
DataGridViewRow Row = new DataGridViewRow();
Row.CreateCells(dataGridView1);
if (myString != null)
dataGridView1.Rows[i].Cells[0].Value = myString;
if (rek != null)
dataGridView1.Rows[i].Cells[1].Value = rek;
if (myvalue != 0)
dataGridView1.Rows[i].Cells[2].Value = myvalue;
if (text1 != null)
dataGridView1.Rows[i].Cells[3].Value = text1;
// int index = this.dataGridView1.Rows.Count;
dataGridView1.Rows.Add(Rows);
}
}
問題:文本框值每次都替換在同一行中,而沒有在新行中進行更新。
第一種方式:
在表格1中,
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm2 = new Form2(dataGridView1.Rows[0].Cells[0].Value.ToString());
frm2.Show();
}
}
表格2
public partial class Form2 : Form
{
public Form2(string s)
{
InitializeComponent();
textBox1.Text = s;
}
}
第二種方式:
public event EventHandler<Form2EventArgs> Form2Event;
public class Form2EventArgs : EventArgs
{
public object Data {get;set;}
}
Event listener in Form1:
private void GetData(object sender, Form2EventArgs args)
{
object data = args.Data;
}
calling the event,
Form2 form2 = new Form2();
form2.Form2Event += GetData;
if(Form2Event != null)
form2Event(this, new Form2EventArgs {Data = data});
創建一個包含您的屬性(模具,...)的類,也許像“ Class1”之類的東西。 將數據作為“列表”緩存在聯系的某個地方,因此操作列表,最后將所有內容都提取到網格中。
您可以使用靜態變量,也可以將其存儲在類中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.