Click here to Skip to main content
15,907,120 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a datagridview that gets populated with some data from an excel file.
I want to be able to populate a textbox with the cell that I have currently selected when I click the button.
I have tried the following but have been unsuccessful in finding a way to do this.
private void btnGetValue_Click(object sender, EventArgs e)
       {

           txtField1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
       }


What I have tried:

txtField1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
Posted
Updated 25-Sep-17 15:31pm
Comments
Karthik_Mahalingam 25-Sep-17 23:20pm    
is the button part of the row?

1 solution

If you are only working with single selection make sure that you set the mode on the DataGridView:
C#
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;

Now, you can work with the SelectedCells property of the dataGridView control:
C#
private void btnGetValue_Click(object sender, System.EventArgs e)
{
    var selectedcell = dataGridView1.SelectedCells?.Count == 1
                           ? dataGridView1.SelectedCells[0]
                           : null;

    if (selectedcell != null)
    {
        // do something with the selected cell...
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900