views:

636

answers:

2

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  A: 

Hello,

replace

grd.Refresh();

by

drv.EndEdit();

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

najmeddine
this solved my problem. wow, i really overlooked that (drv.EndEdit), guess i get used to not calling .EndEdit, it is automated in my subclassed Form. thanks very much ^_^
Hao
A: 

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

CodeByMoonlight