I have form1 with datagridview and a button. When i click a button, a new form opens up where there is a textbox and also a button. In this textbox i can write query and with a click of a button query results are shown in form1 datagridview. The problem is that it opens up another instance of form1 , but i would like that form1 stays open the whole time and only records in datagridview are changing, according to the query input in form2. Both form1 and form2 needs to be opened and active when called.
Here is my code:
//FORM 1
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var queryForm = new Form2();
queryForm.Show(this);
}
//FORM 2
public Form2()
{
InitializeComponent();
}
private SqlConnection Conn;
private void Form1_Load(object sender, EventArgs e)
{
Conn = new SqlConnection(@"Data Source=srvr;Initial Catalog =db; User ID =user; Password =pass");
}
private void btnExecute_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Show(this);
frm1.Activate();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = txtQuery.Text;
try
{
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
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);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
finally
{
Conn.Close();
}
}