更新时如何刷新数据网格视图?来自C#的窗口

时间:2016-11-07 08:20:29

标签: c# visual-studio-2015

我试图在用户将一些项目插入数据库后刷新数据网格视图。我试图取消视图的数据源并为其应用新的数据源,但它没有用。

以下是系统的流程:

  1. 点击添加项目,然后弹出add-item form
  2. 输入产品详细信息,然后单击按钮以插入数据
  3. 查看更新< -----问题
  4. enter image description here

    在此部分中,将有two forms和一个database claee。它们是Form1(数据视图),Add-item formdatabase_function.cs

    以下是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;
        }
    }
    

    以下是form1上的代码:        //在加载form1时获取数据源        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");
        }
    

    以下是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();
            }
        }
    

    但是,我调试日志会显示refresh,这意味着它可以在refresh_dataGridView()中运行。但它无法刷新观点。

    有什么问题?或者有另一种方法可以做到这一点? 感谢

4 个答案:

答案 0 :(得分:2)

您最好重构代码并将数据库访问代码分离到单独的类文件中。那么你可以从其他类,表格等中调用这些函数。

在插入项方法之后的表单中,您可以设置gridview数据源,例如:

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

您需要两种方法,一种用于插入,另一种用于获取详细信息

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;
    }

}

答案 1 :(得分:1)

当您调用database_connect方法时,请使用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();
    }
}

然后,在方法中添加参数Form1 form1,如下所示,并使用相同的引用调用form1.refresh_dataGridView()

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();
    }

另外,更改以下代码以刷新数据网格视图

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

答案 2 :(得分:0)

这是我用于我的代码:

    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;
        }
    }

在我的情况下,我希望在对子窗体进行修改后触发更新,然后返回到我的datagridview所在的主窗体。我使用布尔类型的全局变量来管理它。

答案 3 :(得分:0)

我假设您在将项目插入数据库时​​关闭“AddItem”表单。 我的建议是在不传递引用的情况下更清楚地通知成功插入,并通过公开表示公开形式的控制

根据查询结果将database_connect方法更改为true/false

public void database_connect(String item_code, String des, String unit, double price)
{
    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 + ")";
        int insertedRows = command.ExecuteNonQuery();

        return insertedRows > 0;
    }
    catch(Exception e)
    {
        Debug.WriteLine(e.Source);
    }
    finally
    {
        connect.Close();
    }

    // false will be returned if exception will be thrown
    return false;
}

如果成功添加了项目,则在AddItem表单集Form.DialogResult属性设置为Ok

public class AddNewItemForm : Form
{
    private void button1_Click(object sender, EventArgs e)
    {
        if (error == true)
        {
            error_msg_form emf = new error_msg_form();
            emf.Show();
        }
        else
        {
            database_function df = new database_function();
            bool isAdded = df.database_connect(item_code_tb.Text,
                                               des_tb.Text, 
                                               unit_tb.Text,
                                               Convert.ToDouble(unit_price_tb.Text));

            if(isAdded)
            {
                this.DialogResult = DialogResult.Ok;
            }
        }
    }             
}

然后在Main表单中使用ShowDialog方法获取成功插入的结果。

public class MainForm: Form
{
    private void ButtonAddItem_Click(object sender, EventArgs e)
    {
        using(var addItemForm = new AddNewItemForm())
        {
            if(addItemForm.ShowDialog() == DialogResult.Ok)
            {
                // here you can update your DataGridView
                this.DataGridView.DataSource = df.get_view();
            }
        }
    }           
}