23

I have 2 forms which are form A and form B,

form A allowes user to insert and update student information.

form b is only a DataGridView and button there.

When I insert student on form A, then I go to form B, the new student did not show on the DataGridView , and if I rerun the program, the new student will appear in form B.

I tried using this on button on form b

datagridview1.refresh();
datagridview1.update();

but it's still not working.


Edited:

My code for inserting a worker

cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,[Position],Photo) values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox6.Text + "','" + dateTimePicker2.Value + "',@Position,@Photo)", con);


        cmd.Parameters.AddWithValue("@Position", comboBox1.SelectedText.ToString());
        conv_photo();

        con.Open();
        int n = cmd.ExecuteNonQuery();
        //cmd.ExecuteNonQuery();
        con.Close();
        if (n > 0)
        {
            MessageBox.Show("Inserted");
            loaddata();

            rno++;
        }
        else
            MessageBox.Show("No Insert");



    }

my Datagridview1(Form2) doesn't automatically update when I inserted a new worker. But if I rerun the application, the new worker appears.

2
  • raise a event in form 2, handle it in form 1 and retrieve the data for your gridview again Commented Mar 20, 2013 at 15:06
  • @NoviceProgrammer, can i have example? Commented Mar 20, 2013 at 15:13

8 Answers 8

29
// Form A
public void loaddata()
{
    //do what you do in load data in order to update data in datagrid
}

then on Form B define:

// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];

private void button1_Click(object sender, EventArgs e)
{
    obj.loaddata();
    datagridview1.Update();
    datagridview1.Refresh();
}
Sign up to request clarification or add additional context in comments.

12 Comments

So i have to create a button on form A.. is it got any other way?
you have to trigger an event on form A that new data enter so the datagrid must be updated...that must be done in Form A...
you can declare the variables of the student you store in Form A as public static and pass it in to Form B when you hit the button in Form B
Sorry, seriously i dont understand, can i have some example?
This means you reload all of the data... shouldn't DataBinding help in this case?
|
5

DataGridView.Refresh and And DataGridView.Update are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.

My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.

A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.

Comments

5

For datagridview in C#, use this code

con.Open();
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from dailyprice";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);

DataTable table = new DataTable();
MyDA.Fill(table);

BindingSource bSource = new BindingSource();
bSource.DataSource = table;


dataGridView1.DataSource = bSource;
con.Close();

It works for show new records in the datagridview.

1 Comment

What worked for me was calling the .Fill() method of the DataAdapter (didn't need anything else to cause the refresh of the DataGridView). Make sure you set the ClearBeforeFill property appropriately before calling Fill.
5

for refresh data gridview in any where you just need this code:

datagridview1.DataSource = "your DataSource";
datagridview1.Refresh();

Comments

3

my datagridview is editonEnter mode . so it refresh only after i leave cell or after i revisit and exit cell twice.

to trigger this iimedately . i unfocus from datagridview . then refocus it.

 this.SelectNextControl(dgv1,true,true,false,true);    
 Application.DoEvents();    //this does magic
 dgv1.Focus();

1 Comment

I just read here (stackoverflow.com/a/5183623/1770778) that you shouldn't use Application.DoEvents(). It can cause a lot of troubles. Use threads instead.
2

putting a quick example, should be a sufficient starting point

Code in Form A

public event EventHandler<EventArgs> RowAdded;

private void btnRowAdded_Click(object sender, EventArgs e)
{
     // insert data
     // if successful raise event
     OnRowAddedEvent();
}

private void OnRowAddedEvent()
{
     var listener = RowAdded;
     if (listener != null)
         listener(this, EventArgs.Empty);
}

Code in Form B

private void button1_Click(object sender, EventArgs e)
{
     var frm = new Form2();
     frm.RowAdded += new EventHandler<EventArgs>(frm_RowAdded);
     frm.Show();
}

void frm_RowAdded(object sender, EventArgs e)
{
     // retrieve data again
}

You can even consider creating your own EventArgs class that can contain the newly added data. You can then use this to directly add the data to a new row in DatagridView

4 Comments

after your MessageBox.Show("Inserted"); call the OnRowAddedEvent(); Make sure you subscribe to the event in the other form
can we talk on skype or msn? skype : JKT msn : [email protected]
void frm_RowAdded(object sender, EventArgs e) { // retrieve data again <=== what should i put for this }
sorry about the delay, you need to put the logic of binding the datagrid again here - so whatever method you called to fill the grid needs to be called again.
0

I wanted to do the exactly same thing.

  public static bool update = false;
  Timer t = null;
  private void RefreshTable()
  {
     t = new Timer();
     t.Interval = 1000;
     t.Tick += new EventHandler(t_Tick);
     t.Enabled = true;
  }

  void t_Tick(object sender, EventArgs e)
  {
     if (update)
        {
           dataGridView.Rows.Clear();
           dataGridView.Refresh();
           setCustomerDetailsTable();
           update = false;
        }
   }

I am using a static variable in the form that contains the dataGridView and access it from form A. when user insert or update details I set the update variable true so that when the next time timer ticks the table updates and set the update as false. That prevent it from updating everytime timer ticks. The setCustomerDetailsTable() is the function that initialy loads the data on Form_Load in my case. I am sure this is not the best way. However I am using this timer to show the clock on the UI as well. So I assign it this task as well. When I call RefreshTable() on Form_Load it does what I wanted.

Comments

-1

Create a small function and use it anywhere

public SqlConnection con = "Your connection string"; 
public void gridviewUpdate()
{
    con.Open();
    string select = "SELECT * from table_name";
    SqlDataAdapter da = new SqlDataAdapter(select, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "table_name");
    datagridview.DataSource = ds;
    datagridview.DataMember = "table_name";
    con.Close();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.