Monday, June 29, 2009

selected row content of a datagridview

c# Code

To select the particular column's value whenever the row selection is changing in the datagridview

[CODE]
Add the handler to OnLoad function of the form

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

//Add Selection changed handler
dbGridView.SelectionChanged += new EventHandler(dbGridView_SelectionChanged);

}


//Whenever the row selection is changed, the text box is filled with the Column 1 data

private void dbGridView_SelectionChanged (object sender, EventArgs e)
{

DataGridView dgv = (DataGridView)sender; //User selected WHOLE ROW (by clicking in the margin)

if (dgv.SelectedRows.Count > 0)
textBox1.Text = (dgv.SelectedRows[0].Cells[0].Value.ToString());

//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0)
textBox1.Text = (dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString());

//User selected a cell, show that cell
if (dgv.SelectedCells.Count > 0)
textBox1.Text =(dgv.SelectedCells[0].Value.ToString());
}

[/CODE]

No comments:

Post a Comment