Friday, December 4, 2009

C# - DatagridView

I was in search of editing cell programmatically.
Here is a simple attempt


using System.Collections.Generic;
using System.Windows.Forms;

namespace testGridView
{
public partial class Form1 : Form
{
List cars;

int currentValue;

public Form1()
{
InitializeComponent();
InitializeCarsCollection();
SetLayoutGrid();
this.dataGridView1.DataSource = cars;
}

private void SetLayoutGrid()
{
this.dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
this.dataGridView1.Dock = DockStyle.Fill;
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;
}

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int editedValue = (int)this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;

if (editedValue != this.currentValue)
{
System.Windows.Forms.MessageBox.Show(this.dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString());
}
}

void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{


if (e.ColumnIndex == 2)
{
this.currentValue = (int)this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;
this.dataGridView1.BeginEdit(true);
}
}

private void InitializeCarsCollection()
{
cars = new List();
cars.Add(new Car { Marque = "Renault", Couleur = "rouge", Cylindree = 6 });
cars.Add(new Car { Marque = "Citroen", Couleur = "bleu", Cylindree = 4 });
cars.Add(new Car { Marque = "Peugeot", Couleur = "vert", Cylindree = 8 });
cars.Add(new Car { Marque = "BMW", Couleur = "jaune", Cylindree = 16 });
}
}
}

No comments:

Post a Comment