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
}
}
replace
grd.Refresh();
by
drv.EndEdit();
the selected row is in edit mode, you have to end it for the sorting to take place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With