update datagridview

本文关键字:datagridview update | 更新日期: 2023-09-27 18:06:22

我有以下代码,我想要做的是更新当我从一个单独的表单添加新记录到我的表,在那一刻我得到所有的表数据,但如果我添加新的数据它是不可见的在这里,但保存在表中,我必须关闭程序并再次运行它保存的数据在datagridview中可见。我的问题是如何更新datagridview,以便表信息在任何时候都在那里。我的代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace project
{
    public partial class frmViewBookings : Form
    {
        public frmViewBookings()
        {
            InitializeComponent();
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            Form3 mainpage = new Form3();
            mainpage.Show();
            this.Close();
        }
        private void frmViewBookings_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
            this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
        }
    }
}

update datagridview

在frmviewbooking中添加/编辑您现有的方法:

private void frmViewBookings_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
    UpdateData();
}
public void UpdateData()
{
    this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}

然后从另一个Form中调用UpdateData()

在另一个表单中,添加一个包含第一个表单的属性:

public partial class frmBooking : Form
{
    public frmViewBookings myBookingsFrm = null;
}

当您创建frmBooking表单时,执行:

frmBooking frmNewBookingFrm = new frmBooking();
frmNewBookingFrm.myBookingsFrm = this;//or whatever reference to the first frmViewBookings is

所以当你在frmBooking中插入新记录后,调用:

myBookingsFrm.UpdateData();