Search code examples
c#winformsdatagridview

Get ID from selected row in DataGridView to print in Textbox


Simply just I want to reflect the Id number in selected row from DataGridView

I have tried this

tb_id.Text = dgv_search.SelectedCells[0].Value.ToString();

tb_id is my textbox and dgv_search is the DataGridView

I got the result of first row even if I select another row


Solution

  • Your words say you want the Id in the selected row but your code says to use the first value in the SelectedCells collection. Try making your code match your intent by using the SelectedRows collection instead.

    dgv_search.SelectionChanged += (sender, e) =>
    {
        if(dgv_search.SelectedRows.Count > 0)
        {
            var rowIndex = dgv_search.SelectedRows[0].Index;
            var columnIndex = dgv_search.Columns["Id"].Index;
            tb_id.Text = dgv_search[columnIndex, rowIndex].Value?.ToString() ?? string.Empty;
        }
    };