The DataGridView.SelectionChanged event appears broken in two places:
First it reports CurrentRow.Selected = false always.
The past tense SelectionChanged should be called
after the selection is done changing completely.
Second, we get two different results if we change the
row by clicking in the datagrid or pressing buttons
and changing the row programatially. If we click
in the datagrid to change the row, the RowIndex is set
to the clicked row. However, if we change the row
programatically, the RowIndex is set to the row we
are leaving.
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;
using System.Diagnostics;
namespace Tester
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += new System.EventHandler(Form1_Load);
}
protected void Form1_Load(object sender, System.EventArgs e)
{
// Add five rows two columns
for ( int x = 0; x < 5; x++ )
{
dataGridView1.Rows.Add("Row: " + x.ToString() + " Col: 1",
"Row: " + x.ToString() + " Col: 2");
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
String selected = dataGridView1.CurrentRow.Selected ? "True" : "False";
int rowIndex = dataGridView1.CurrentCell.RowIndex;
Debug.WriteLine("RowIndex: " + rowIndex.ToString() );
Debug.WriteLine("selected: " + selected );
Debug.WriteLine("=========================================");
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.CurrentCell = dataGridView1[0, 3];
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.CurrentCell = dataGridView1[0, 2];
}
}
}