更改后从其他用户控件刷新用户控件中的DataGridView

本文关键字:控件 用户 DataGridView 刷新 其他 | 更新日期: 2023-09-27 18:26:36

我的用户控件中有一个DataGridView,我想在进行更改时刷新它。例如,当我在另一个用户控件中单击保存按钮时,应该调用具有DataGridView的用户控件中的刷新函数。我已经搜索了这个问题的解决方案,但没有一个解决我的问题(我尝试了ResetBindings,将DataSource设置为null并再次设置DataSource等)。要从另一个用户控件调用用户控件,我使用实例。

   public partial class incidentTypeSearchControl : UserControl
{
    public static incidentTypeSearchControl Instance { get; set; }
    REINVENT_QualityDataSet reinventQualityDataset = new REINVENT_QualityDataSet();
    SqlCommand cmd = new SqlCommand();
    BindingSource source = new BindingSource();
    REINVENT_QualityDataSetTableAdapters.IncIncidentTypeTableAdapter incidentTypeAdapter =
        new REINVENT_QualityDataSetTableAdapters.IncIncidentTypeTableAdapter();
    public incidentTypeSearchControl()
    {
        InitializeComponent();
        Instance = this;
        this.dataGridView1.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellDoubleClick);
    }
    private void incidentTypeSearchControl_Load(object sender, EventArgs e)
    {                   
        incidentTypeAdapter.Fill(reinventQualityDataset.IncIncidentType);
        source.DataSource = reinventQualityDataset.IncIncidentType;
        dataGridView1.AutoGenerateColumns = true;           
        //dataGridView1.DataSource = reinventQualityDataset.IncIncidentType;
        dataGridView1.DataSource = source;
        dataGridView1.Columns[0].HeaderText = "Id";
        dataGridView1.Columns[1].HeaderText = "Incidenttype";
        dataGridView1.Columns[2].HeaderText = "Categorie";
        dataGridView1.Columns[3].HeaderText = "Tellen in statistiek";
        dataGridView1.Columns[4].HeaderText = "Punten";            
        dataGridView1.Columns[5].HeaderText = "Faalkosten";
        dataGridView1.Columns[6].HeaderText = "Kostendrager";
        for (int i = 0; i < 6; i++)
        {
            dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        }          
        dataGridView1.Columns[6].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;
    }
    //added/      
    public DataGridView myDataGrid
    {
        get { return dataGridView1; }
        set { dataGridView1 = value; }
    }
    public void updateDataGridView()
    {
        dataGridView1.DataSource = null;
        dataGridView1.DataSource = source;
        source.ResetBindings(true);
    }

在其他用户控制中,我可以访问这样的数据网格视图:

    incidentTypeSearchControl.Instance.myDataGrid // access datagridview

调用updateGridView()方法会将网格头文本设置回默认值(这不是目的),并且数据网格视图中的值不会更新。如何制作方法刷新/更新我的datagridview并从我的其他用户控件调用此方法?

更新:

通过再次填充数据集解决问题

更改后从其他用户控件刷新用户控件中的DataGridView

尝试

dataGridView1.DataSource = typeof(IncIncidentTypeDataTable); // or whatever type is your source
dataGridView1.DataSource = source;