当在创建客户表单中添加客户时,如何在MainForm中更新Datagridview?

问题描述 投票:0回答:1

我正在尝试在MainForm的datagridview中显示数据。我在创建客户表单中添加客户。

private void createButton_Click(object sender, EventArgs e)
{
    string timestamp = Info.createTimestamp();
    string userName = Info.getCurrentUserName();
    if (string.IsNullOrEmpty(countryTxtBx.Text) ||
        string.IsNullOrEmpty(cityTxtBx.Text) ||
        string.IsNullOrEmpty(addressTxtBx.Text) ||
        string.IsNullOrEmpty(cityTxtBx.Text) ||
        string.IsNullOrEmpty(zipTxtBx.Text) ||
        string.IsNullOrEmpty(phoneTxtBx.Text) ||
        string.IsNullOrEmpty(nameTxtBx.Text) ||
        (yesButton.Checked == false && noButton.Checked == false))
    {
        MessageBox.Show("Please enter all fields");
    }
    else
    {
        int countryId = Info.createRecord(timestamp, userName, "country", $"'{countryTxtBx.Text}'");
        int cityId = Info.createRecord(timestamp, userName, "city", $"'{cityTxtBx.Text}', '{countryId}'");
        int addressId = Info.createRecord(timestamp, userName, "address", $"'{addressTxtBx.Text}', '', '{cityId}', '{zipTxtBx.Text}', '{phoneTxtBx.Text}'");
        Info.createRecord(timestamp, userName, "customer", $"'{nameTxtBx.Text}', '{addressId}', '{(yesButton.Checked ? 1 : 0)}'");
        Close();
    }
}

我能够从MySql中提取数据,但是当我添加或删除客户时,MainForm中的datagridview不会更新。当我在“创建客户表单”中添加客户时,有什么方法可以更新主表单中的datagridview?

public void DataFill()
{
    // Open connection
    MySqlConnection conn = new MySqlConnection(Info.conString);
    conn.Open();

    // Create new DataAdapter
    string query = $"SELECT * FROM customer";
    MySqlDataAdapter SDA = new MySqlDataAdapter(query, conn);
    DataTable dt = new DataTable();
    SDA.Fill(dt);
    // Render data onto the screen
    customerDGV.DataSource = dt;
}
c# mysql datagridview
1个回答
0
投票

您每次添加或删除客户时都可以刷新MainForm的DataGridView。这是实现这一目标的一种方法...

//event to open the create customer form
private void OpenCreateCustomerForm(){
//first, create an instance of the form
frmCreateCustomer frm = new frmCreateCustomer();
/*second, add the function DataFill() to the FormClosed event of the create customer form, so everytime you close it, the MainForms datagridview will get updated*/
frm.FormClosed += new FormClosedEventHandler((object s, FormClosedEventArgs f) => { DataFill();});
//finally, show the create customer form
frm.ShowDialog();
};
© www.soinside.com 2019 - 2024. All rights reserved.