How to force refresh the DataGridView's conten

2019-02-17 15:10发布

I want to make a sorted datagridview input. The following code snippet doesn't quite cut it; even if i put a grd.Refresh, the datagridview doesn't show its updated values. If i press arrow down key and go up again, the grid is refreshing. Is there any other way i can force refresh to datagridview's content?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TestSortedInput
{
    public partial class Form1 : Form
    {
        DataTable _dt = new DataTable();

        public Form1()
        {
            InitializeComponent();

            grd.AllowUserToAddRows = false;

            _dt.Columns.Add("sort", typeof(int));
            _dt.Columns.Add("product", typeof(string));

            _dt.DefaultView.Sort = "sort";

            grd.DataSource = _dt;
        }

        private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Insert)
            {                
                if (e.Modifiers == 0)
                {
                    var r = _dt.NewRow();
                    r["sort"] = _dt.DefaultView.Count + 1;
                    r["product"] = "";

                    _dt.Rows.Add(r);
                }
                else if (e.Alt)
                {
                    var drv = this.BindingContext[_dt].Current as DataRowView;

                    int sort = (int)drv["sort"];

                    for (int i = _dt.DefaultView.Count - 1; i >= (int)drv["sort"] - 1; --i)
                    {                        
                        _dt.DefaultView[i]["sort"] = (int) _dt.DefaultView[i]["sort"] + 1;                        
                    }

                    var r = _dt.NewRow();
                    r["sort"] = sort;

                    _dt.Rows.Add(r);

                    grd.Refresh();
                }
            }
        }//void
    }
}

2条回答
该账号已被封号
2楼-- · 2019-02-17 15:48

Have you tried using a BindingSource with the source as the datatable, and then calling the BindingSource's ResetBindings method?

查看更多
Root(大扎)
3楼-- · 2019-02-17 15:49

replace

grd.Refresh(); 

by

drv.EndEdit();

the selected row is in edit mode, you have to end it for the sorting to take place.

查看更多
登录 后发表回答