简体   繁体   中英

Not able to update datagridview data in windows form application C#

I have two forms in my windows form application. I have a datagridview in form1, I am able to update the data of the datagridview from the form1. Now, i need to update the datagridview from form2. I am calling the same method from form2 which i am using to update the datagridview from form1.

While calling the method from form2, in debugging i can see that it updating the datasource of the datagridview, but it not updating the data on UI.

I know it is a repeat question. I have tried many different ways. I have also tried the concept of MdiContainer, but not useful for me.

I have below methods in form1 which doing job to update data of datagridview(CustomerList) and it updating the datagridview on UI also while calling BindCustomerList() method from form1

//form1
public void BindCustomerList()
{
     CustomerList.AutoGenerateColumns = false;
     CustomerList.DataSource = FetchEmpDetails();
     CustomerList.ClearSelection();
}

public DataTable FetchEmpDetails()
{
      if (sqlCon.State == ConnectionState.Closed)
      {
            sqlCon.Open();
      }
      DataTable dtData = new DataTable();
      sqlCmd = new SqlCommand("sp_customers", sqlCon);
      sqlCmd.CommandType = CommandType.StoredProcedure;
      sqlCmd.Parameters.AddWithValue("@ActionType", "FetchData");
      SqlDataAdapter sqlSda = new SqlDataAdapter(sqlCmd);
      sqlSda.Fill(dtData);
      return dtData;
}

I am calling BindCustomerList() from form2 using below code, which updating the datasource of the datagridview(CustomerList) but not updating on UI in form1.

//form2 button click event    
private void btnSave_Click(object sender, EventArgs e)
{
    Form1 form1 = new Form1();    //object of form1 in form2
    this.Close();                 //closing form2 on button click
    form1.BindCustomerList();     //calling form1 method to update datagridview.
}

Make your form2 constructor accept a datatable parameter, and assign it to the DataSource of the other grid:

public Form2(DataTable dt){
  InitializeComponent();

  otherDataGridView.DataSource = dt;
}

And when you make a new Form2, in form1, after you already called BindCustomerList at least once:

var f = new Form2(CustomerList.DataSource as DataTable);

I am calling BindCustomerList() from form2

It won't work; bindCustomerList sets the DataSource of form1's datagridview; this is nothing to do with form2. To have the forms share data you have to pass the data you want to share, such as in my code above (for example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM