问题
I have two Windows Forms (Form1
and Form2
). Form1
has a button (openfrm2
) and a datagridview (dataGridView1
). Form2
has a textbox (sql_textbox
) and a button (button1
).
Clicking on openfrm2
opens Form2
, then I'm writing an SQL query in sql_textbox
to view a table in a Postgres database and clicking on button1
should show the result of the query in dataGridView1
. But it doesn't.
Here is my code:
Form1:
public BindingSource bindingSource1 = new BindingSource();
private void openfrm2_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
Form2:
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.bindingSource1.DataSource = query();
frm1.dataGridView1.DataSource = frm1.bindingSource1;
}
DataTable query()
{
NpgsqlConnectionStringBuilder cnsb = new NpgsqlConnectionStringBuilder();
cnsb.Database = "postgres";
cnsb.Username = "postgres";
cnsb.Password = "root";
cnsb.Host = "localhost";
DataTable dt = new DataTable();
using (NpgsqlConnection cnn = new NpgsqlConnection(cnsb.ConnectionString))
{
cnn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql_textbox.Text, cnn))
{
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql_textbox.Text, cnn);
da.Fill(dt);
}
}
return dt;
}
I tried the solutions written at similar questions, but nothing works. If I add a datagridview to Form2
, and add this
dataGridView2.DataSource = frm1.bindingSource1;
line to button1_Click
it shows the data, but I need to display it on Form1
.
How can I do it?
来源:https://stackoverflow.com/questions/50159119/c-sharp-datagridview-doesnt-show-data-on-other-form