2

Is it possible to replace an entire DataGridViewRow value in one line of code?

Dim dgvR As DataGridViewRow = dgvExcelData.Rows(i)
'[...]
Dim row As String() = New String() {a,b,c,d,e}

I don't want to replace like this:

dgvR.Cells("xxx").Value = a
Jimi
  • 29,621
  • 8
  • 43
  • 61
KSA
  • 675
  • 1
  • 5
  • 9

1 Answers1

2

You can use the DataGridViewRow.SetValues method.
It accepts an object[]:

dataGridView1.Rows[1].SetValues(new object[] { 1, "2", 3.01D, DateTime.Now, null });

This object array can also be set when the DataGridView is bound to a DataSource.
Make sure the objects in the array correspond to each Cell's ValueType.

Jimi
  • 29,621
  • 8
  • 43
  • 61
  • Is there a way to replace the row values using a class instead of `new object[]`. For instance, assume that we have this `personObj` from the class `PersonDto`, how can we pass it into the `datagridview1`? `dataGridView1.Rows[1].SetValues(personObj )` doesn't seem to work. – Ruslan May 28 '21 at 07:09
  • 1
    @rushas You need to implement this functionality in your class object, to achieve a result similar to the `ToString()`, `GetHashCode()` and `Equals()` overrides. E.g., add a `ToDataObject()` public method which returns a `new object[]{ }`. This array stores the class's Property values in the order in which they're declared. You can then set the values with, e.g., `[DataGridView].CurrentRow.SetValues([YouClassObject].ToDataObject());` – Jimi May 28 '21 at 11:22