0

I need to get the value of a selected cell on a datagridview when the user clicks on it.

I've tried to bring the value to a textbox to test the click event but when I click on it, the textbox doesn't show the cell value.

 private void btnsync_Click(object sender, EventArgs e) //Obtiene el catálogo de presupuestos

    {
        SqlConnection conn = new SqlConnection(@"Data Source=.\MYINSTANCE;Integrated Security=True;MultipleActiveResultSets=True");
        string cmd = "SELECT name FROM master.dbo.sysdatabases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');";

        var dataAdapter = new SqlDataAdapter(cmd, conn);
        var commandBuilder = new SqlCommandBuilder(dataAdapter);
        var ds = new DataSet();
        dataAdapter.Fill(ds);
        dataGridView1.ReadOnly = true;
        dataGridView1.DataSource = ds.Tables[0];

    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            dataGridView1.CurrentRow.Selected = true;
            txtpresup.Text = dataGridView1.Rows[e.RowIndex].Cells["name"].FormattedValue.ToString();
        }


    }

I expect that the "textpresup" text box is filled with the value of the selected cell.

Gabo RM
  • 41
  • 1
  • 1
  • 3

2 Answers2

0

What you're looking for is

DataGridView.SelectedRows[0].Cells[0].Value.ToString();

Don't forget to change Cells[0] to either the column index (eg Cells[4]) or the column name (eg Cells["Name"])

However, if this code is triggered and no cell/row has been selected you're likely to get a null reference error

Mark
  • 691
  • 7
  • 20
  • well this was useful to get it right, but I had an exception of an index out of range, thanks for the answer! – Gabo RM Jun 05 '19 at 21:09
0

Solved

  private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.SelectedCells.Count > 0)
            {
                int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;

                DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
                string value = selectedRow.Cells["name"].Value.ToString();

                txtpresup.Text = value;
            }
        }
    }
Gabo RM
  • 41
  • 1
  • 1
  • 3