2 回答
TA貢獻(xiàn)1860條經(jīng)驗 獲得超8個贊
好吧,既然你在打電話Form1 frm1 = new Form1();- 你還期待opens up another instance of form1什么?- 為什么不應(yīng)該new Form1()產(chǎn)生另一個實例?
您將需要獲取已創(chuàng)建的Form1.
例如,請參見 在 c# windows 應(yīng)用程序中查找打開的表單
當(dāng)你找到它時,你可以激活它,例如:
var frm1 = Application.OpenForms[0];
//frm1.Show(this); <- don't need to call Show since its already open
frm1.Activate();
你也應(yīng)該改變你btnExecute_Click的。
private void btnExecute_Click(object sender, EventArgs e)
{
var frm1 = Application.OpenForms[0] as Form1; //find `Form1` like you want, I only take [0]
//always create a new instance of SqlConnection here and dispose it with the using Keyword
//don't use a private field to try to keep the Connection, let the internal Connection pool handle that case
using (var con = new SqlConnection(@"Data Source=srvr;Initial Catalog =db; User ID =user; Password =pass"))
{
try
{
con.Open();
//clean up, Command/Reader with using keyword
using (var cmd = con.CreateCommand())
{
cmd.CommandText = txtQuery.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
//read data
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
}
//should activate the `Form1` AFTER the job is done, you can consider if you only want to activate it if the previous Code didn't fail
frm1.Activate();
}
不要真正了解您在“read_data”例程中所做的事情。
此代碼塊:
frm1.dataGridView1.Columns.Clear();
frm1.dataGridView1.Rows.Clear();
if (reader.HasRows)
{
DataTable schema = reader.GetSchemaTable();
int field_num = 0;
foreach (DataRow schema_row in schema.Rows)
{
int col_num = frm1.dataGridView1.Columns.Add(
"col" + field_num.ToString(),
schema_row.Field<string>("ColumnName"));
field_num++;
frm1.dataGridView1.Columns[col_num].AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
}
object[] values = new object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(values);
frm1.dataGridView1.Rows.Add(values);
}
}
嘗試以下是否足夠,將上面代碼中的我的注釋“//讀取數(shù)據(jù)”替換為:
frm1.dataGridView1.AutoGenerateColumns = true; //say to automatically create columns, based on the result inside the datatable
frm1.dataGridView1.Columns.Clear();
var dataTable = new DataTable();
dataTable.Load(dataReader); //load the SqlDataReader into the DataTable
frm1.dataGridView1.DataSource = dataTable; //set the dataGridView's DataSource to the dataTable
TA貢獻(xiàn)1757條經(jīng)驗 獲得超8個贊
在 form1 中單擊按鈕時,您可以簡單地打開 form2 的一個新實例并在那里完成您的工作,并在關(guān)閉時在 form1 中接收該值?;蛘吣梢酝ㄟ^構(gòu)造函數(shù)將 form1 的實例傳遞到 form2 并從 form2 更新 form1。例如:
var isFormClosed = false;
using(form1 frm = new form1())
{
// do something here
frm.ShowDialog();
isFormClosed = true;
}
或者,如果您希望將 form1 的引用傳遞給 form2,
var isFormClosed = false;
using(form1 frm = new form1(this))
{
// do something here
frm.ShowDialog();
isFormClosed = true;
}
在這里,在 form2 中,您可以簡單地使用 form1 的傳遞引用來更新屬性或網(wǎng)格。
- 2 回答
- 0 關(guān)注
- 176 瀏覽
添加回答
舉報
