简体   繁体   中英

How to update datagridview in C# after adding record nayf button?

It's my code button load on datagridview data with my database in SQL Server. After a click on the button, I want to update data in the datagridview. How can I do this?

public void load_data_Click(object sender, EventArgs e)
{
        string text = "way_on_sql";
        SqlConnection conn = new SqlConnection(text);

        try
        {
            DataTable sotrud_table = new DataTable("Sotrud");  
            SqlDataAdapter load_table_sotrud = new SqlDataAdapter("SELECT * FROM sotrud", conn);

            load_table_sotrud.FillSchema(sotrud_table, SchemaType.Source);
            load_table_sotrud.Fill(sotrud_table);

            ds.Tables.Add(sotrud_table);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        try
        {
            if (ds.Tables.Count != 0)
            {
                grid_sotrud.DataSource = ds.Tables["Sotrud"].DefaultView;
                grid_sotrud.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                grid_sotrud.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                grid_sotrud.MultiSelect = false;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

This my button update code - and this does not work:

private void update_data_Click(object sender, EventArgs e)
{
    grid_sotrud.DataSource = ds.Tables["Sotrud"].DefaultView;
    grid_sotrud.Refresh();
}

/* try calling the function that loads data from the database and displays in table instead of refreshing the table */

private void update_data_Click(object sender, EventArgs e)
{
    grid_sotrud.DataSource = ds.Tables["Sotrud"].DefaultView;
    load_data_Click();
}

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