mover filas en datagridview
Publicado por
Gualterio (1 intervención) el 23/11/2011 21:52:41
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<MyItem> items = new List<MyItem> {
new MyItem {Id = 0, Name = "Hello"},
new MyItem {Id = 1, Name = "World"},
new MyItem {Id = 2, Name = "Foo"},
new MyItem {Id = 3, Name = "Bar"},
new MyItem {Id = 4, Name = "Scott"},
new MyItem {Id = 5, Name = "Tiger"},
};
private BindingSource bs;
private void Form1_Load(object sender, EventArgs e)
{
bs = new BindingSource(items, string.Empty);
dataGridView.DataSource = bs;
//DataGridViewRow dr = new DataGridViewRow();
//string[] row1 = new string[] { "CAMPO001"};
//this.dataGridView.Rows.Add(row1);
//string[] row2 = new string[] { "CAMPO002" };
//this.dataGridView.Rows.Add(row2);
//string[] row3 = new string[] { "CAMPO003"};
//this.dataGridView.Rows.Add(row3);
//string[] row4 = new string[] { "CAMPO004" };
//this.dataGridView.Rows.Add(row4);
//string[] row5 = new string[] { "CAMPO005" };
//this.dataGridView.Rows.Add(row5);
//string[] row6 = new string[] { "CAMPO006" };
//this.dataGridView.Rows.Add(row6);
//this.dataGridView.RowHeadersVisible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int position = bs.Position;
if (position == 0) return; // already at top
bs.RaiseListChangedEvents = false;
MyItem current = (MyItem)bs.Current;
bs.Remove(current);
position--;
bs.Insert(position, current);
bs.Position = position;
bs.RaiseListChangedEvents = true;
bs.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
int position = bs.Position;
if (position == bs.Count - 1) return; // already at bottom
bs.RaiseListChangedEvents = false;
MyItem current = (MyItem)bs.Current;
bs.Remove(current);
position++;
bs.Insert(position, current);
bs.Position = position;
bs.RaiseListChangedEvents = true;
bs.ResetBindings(false);
}
public class MyItem
{
public int Id { get; set; }
public String Name { get; set; }
}
}
}