Celcius_Bitz Celcius_Bitz - 3 months ago 9
MySQL Question

C# Mysql Search in Form1 and show result in form2

i have form1 that have searchToolStripTextBox, an invisible(visible=false) btnSearch, panel1(for loading form2) and dataToolStripMenuItem(showing form2). While form2 have dgvData(datagridview) which connected to mysql

the problem is i want to search someone name using searchToolStripTextBox(when i press enter, btnSearch will trigger) in form1 and form2 dgvData will select it

here's my code(in form1)

private void dataToolStripMenuItem_Click(object sender, EventArgs e)
{
FData FD = new FData();
FD.TopLevel = false;
panel1.Controls.Clear();
panel1.Controls.Add(FD);
FD.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
FD.Dock = DockStyle.Fill;
FD.Show();
formtoolStripStatusLabel.Text = "Data";
}

private void btnSearch_Click(object sender, EventArgs e)
{
FData FD = new FData();

MySqlConnection con = new MySqlConnection(MyConnectionString);
con.Open();
try
{
MySqlCommand cmd = con.CreateCommand();
cmd.CommandText = "Select * from tb_pasien where Pasien = '" + searchtoolStripTextBox.Text + "';";


MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
FD.dgvData.DataSource = ds.Tables[0].DefaultView;

}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Clone();
}
}
}

private void searchtoolStripTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnSearch_Click(this, new EventArgs());
}
}
}


thanks before.

Answer

You're creating and showing a form in the dataToolStripMenuItem_Click method:

FData FD = new FData();
//...
FD.Show();

But then in the btnSearch_Click method you create an entirely new form, which you never show, and send your data to that one:

FData FD = new FData();
//...
FD.dgvData.DataSource = ds.Tables[0].DefaultView;

Changes made to an instance of an object don't affect other instances of that object.

Instead, make your form reference a class-level member. Something like this:

FData FD = new FData();

private void dataToolStripMenuItem_Click(object sender, EventArgs e)
{
    //...
    FD.Show();
}

private void btnSearch_Click(object sender, EventArgs e)
{
    //...
    FD.dgvData.DataSource = ds.Tables[0].DefaultView;
}

That way there's only one instance of the FData form and you're both showing and interacting with that same instance.

Comments