How to refresh the data grid view when update? Window from C#

I am trying to refresh the data grid view after the user insert some item to the database. And I tried to null the data source of the view and apply a new data source to it, but it didn't work.

Here is the flow of the system:

  • Click the add Item, then pop-up a add-item form
  • Input the product detail, then click the button to insert data
  • View update <-----Problem
  • 在这里输入图像描述

    In this part, there will have two forms and one database claee . They are Form1 (the data view), Add-item form and the database_function.cs .

    Here is my code on database class :

      public class database_function
    {
       OleDbConnection connect = new OleDbConnection();
    
    
        public database_function()
        {
            connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:sys_db.accdb";
        }
    
        public void database_connect(String item_code, String des, String unit, double price)
        {
          Form1 f1 = new Form1();
            try
            {
    
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connect;
                command.CommandText = "INSERT into item (item_code, description, unit, price) values ('" + item_code + "', '" + des + "', '" + unit + "', " + price + ")";
                command.ExecuteNonQuery();
    
                connect.Close();
            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Source);
                connect.Close();
            }
           f1.refresh_dataGridView();
        }
    
    
    
        //return the dataGridView to form 1, and show the database data on it.
        public DataTable get_view()
        {
            connect.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connect;
            string query = "Select item_code, description, unit, price from item";
            command.CommandText = query;
    
            OleDbDataAdapter da = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            da.Fill(dt);
            connect.Close();
            Debug.WriteLine("return dataTable");
            return dt;
        }
    }
    

    Here is the code on form1 : //Get the data source when the form1 is loading private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = df.get_view();
    }

       //Refresh the view
       public void refresh_dataGridView()
        {
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = df.get_view();
            Debug.WriteLine("refuesh");
        }
    

    Here is the add-item. form add-item. form :

    private void button1_Click(object sender, EventArgs e)
        {
           //Get textfield data....
    
            //If user doesn't input the item data, show the error message. Else, update to database.
            if (error == true)
            {
                error_msg_form emf = new error_msg_form();
                emf.Show();
            }
            else
            {
                Form1 f1 = new Form1();
                database_function df = new database_function();
                 df.database_connect(item_code_tb.Text, des_tb.Text, unit_tb.Text, Convert.ToDouble(unit_price_tb.Text));
                //f1.refresh_dataGridView();
            }
        }
    

    However, I debug log will show the refresh , that mean it can run in the refresh_dataGridView() . But it cannot refresh the view.

    What is the problem is it? Or there have another way to do this? Thanks


    When you call the database_connect method, pass the form reference as below with this ,

    private void button1_Click(object sender, EventArgs e)
    {
       //Get textfield data....
    
        //If user doesn't input the item data, show the error message. Else, update to database.
        if (error == true)
        {
            error_msg_form emf = new error_msg_form();
            emf.Show();
        }
        else
        {
            //Form1 f1 = new Form1();
            database_function df = new database_function();
             df.database_connect(this, item_code_tb.Text, des_tb.Text, unit_tb.Text, Convert.ToDouble(unit_price_tb.Text));
            //f1.refresh_dataGridView();
        }
    }
    

    Then, add the parameter Form1 form1 in the method as below and call form1.refresh_dataGridView() using the same reference.

    public void database_connect(Form1 form1, String item_code, String des, String unit, double price)
        {
          //Form1 f1 = new Form1();
            try
            {
    
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connect;
                command.CommandText = "INSERT into item (item_code, description, unit, price) values ('" + item_code + "', '" + des + "', '" + unit + "', " + price + ")";
                command.ExecuteNonQuery();
    
                connect.Close();
            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Source);
                connect.Close();
            }
           form1.refresh_dataGridView();
        }
    

    Also, change the code as below to refresh the data grid view,

    public void refresh_dataGridView()
        {
            dataGridView1.DataSource = typeof(List);
            dataGridView1.DataSource = df.get_view();
            Debug.WriteLine("refuesh");
        }
    

    You better refactor your code and separate database access code into separate class file. then you can call those functions from other classes, forms etc..

    In your Form just after insert item method you can set the gridview data source, for example:

    database_function df = new database_function();
    df.InsertItem("sdfsdf", "Description", "KG", 5);
    //load data again
    dataGridView1.DataSource = df.get_view();
    

    you need two methods, one for insert and one for get details

    public class database_function
    {
         public void InsertItem(String item_code, String des, String unit, double price)
            {
               //Form1 f1 = new Form1();
                try
                {
                    connect.Open();
                    OleDbCommand command = new OleDbCommand();
                    command.Connection = connect;
                    command.CommandText = "INSERT into item (item_code, description, unit, price) values ('" + item_code + "', '" + des + "', '" + unit + "', " + price + ")";
                    command.ExecuteNonQuery();
    
                    connect.Close();
                }
                catch(Exception e)
                {
                    Debug.WriteLine(e.Source);
                    connect.Close();
                }
             //f1.refresh_dataGridView();
            }
    
     public DataTable get_view()
        {
            connect.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connect;
            string query = "Select item_code, description, unit, price from item";
            command.CommandText = query;
    
            OleDbDataAdapter da = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            da.Fill(dt);
            connect.Close();
            return dt;
        }
    

    }


    This is the code I used for mine:

        private void Form1_Activated(object sender, EventArgs e) {
            if (GlobalVariables.bReload == false) {
                Activated -= Form1_Activated;
                GlobalVariables.bReload = true;
                dgv1.DataSource = "my datasource"
                dgv1.Refresh();
                Activated += Form1_Activated;
            }
        }
    

    In my case I wanted to trigger the update it after I made a modification on a subform and came back to the main form where my datagridview was located. I used a boolean type global variable to manage it.

    链接地址: http://www.djcxy.com/p/71168.html

    上一篇: 当dataGridView行匹配文本框时显示错误消息

    下一篇: 更新时如何刷新数据网格视图? C#窗口