How to change selected cell in DataGridView on selection

With a list box, I have the following code to retrieve the selected item:

    private void inventoryList_SelectedIndexChanged(object sender, EventArgs e)
    {
        String s = inventoryList.SelectedItem.ToString();
        s = s.Substring(0, s.IndexOf(':'));
        bookDetailTable.Rows.Clear();
        ...
        more code
        ...
    }

      

I want to do something similar for the DataGridView, that is, when the selection changes, get the content of the first cell in the selected row. The problem is I don't know how to access this data item.

Any help is greatly appreciated.

+3


source to share


2 answers


I think this is what you are looking for. But if not, hopefully this will get you started.



private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    //User selected WHOLE ROW (by clicking in the margin)
    if (dgv.SelectedRows.Count> 0)
       MessageBox.Show(dgv.SelectedRows[0].Cells[0].Value.ToString());

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

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

      

+14


source


This is another way to approach this question using the column name.

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
   var senderGrid = (DataGridView)sender;
   if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
   {
      if (e.ColumnIndex == dataGridView1.Columns["ColumnName"].Index)
      {
        var row = senderGrid.CurrentRow.Cells;
        string ID = Convert.ToString(row["columnId"].Value); //This is to fetch the id or any other info
        MessageBox.Show("ColumnName selected");
      }
   }
}

      



If you need to pass data from this selected row, you can pass it this way to another form.

Form2 form2 = new Form2(ID);
form2.Show();

      

0


source







All Articles