【发布时间】:2017-08-23 04:44:01
【问题描述】:
当我运行我的桌面应用程序时,首先打开我的桌面应用程序 form1,当单击数据网格 view1 的一行时,打开了 form2 的一个实例。form2 有几个文本框,当我填充它们并单击按钮时,将显示这些值在form1的数据网格视图2中!
下面给出form1的代码
public partial class Form1 : Form
{
string dbconnection;
public Form1()
{
InitializeComponent();
dbconnection = @" Data Source = D:\SQLite\SQLiteStudio\DB1.db ; version=3 ";
}
private static Form1 f1;
public static Form1 getInstance(){
if (f1 == null)
{
f1 = new Form1();
}
else
f1.BringToFront();
return f1;
}
private void loadButton_Click(object sender, EventArgs e)
{
{
using (SQLiteConnection con = new SQLiteConnection(dbconnection))
{
try
{
con.Open();
if (con.State == ConnectionState.Open)
{
string sql = "select MESSAGE_ID from Message";
SQLiteCommand command = new SQLiteCommand(sql, con);
SQLiteDataReader reader = command.ExecuteReader();
//dataGridView1.ColumnCount = 1;
// dataGridView1.Columns[0].Name = "Message ID";
DataTable ds = new DataTable();
ds.Load(reader);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
dataGridView1.Refresh();
}
}
catch (Exception m)
{
MessageBox.Show(m.Message);
}
}
}
}
public void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Form2 f2 = new Form2();
f2.IDtext.Text = row.Cells["MESSAGE_ID"].Value.ToString();
f2.ShowDialog();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
下面是form2的代码
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/* if (f1 == null)
{
f1 = new Form1();
} */
Form1 f1x = Form1.getInstance();
DataTable dt1 = new DataTable();
f1x.dataGridView2.DataSource = dt1;
dt1.Columns.Add("MessageID", typeof(string));
dt1.Columns.Add("Name", typeof(string));
dt1.Columns.Add("Number", typeof(string));
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text; ;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
dt1.Rows.Add(dr);
f1x.Show();
}
}
我在 form1 中编写了一个名为 getinstance() 的方法来实现这一点,但会打开一个新窗口。 我希望这些值出现在我最初加载的 form1 中,但数据显示在 form1 的新实例中。如何在我加载的初始 form1 中显示数据
【问题讨论】:
-
在调用
Form1.getInstance之前,您从未在Form1中设置f1,因此您明确地创建了一个新的Form1。创建时,为什么不简单地将现有Form1的引用传递给“Form2”?或者,您可以将一个事件添加到您在Form1中处理的Form2。 -
@oerkelens 你能给它一个代码sn-p吗?