Search code examples
vb.netwinformsdatagridview

How to add a new DataGridViewRow with customized font color and font size


How to add new DataGridViewRow with customized Font color and Font size?

I have a DataGridView with 5 columns.

I'm using this code but it causes an index out of range exception:

Dim NewR As DataGridViewRow = New DataGridViewRow

NewR.Cells(0).Value = ""
NewR.Cells(1).Style.ForeColor = Color.BlueViolet
NewR.Cells(1).Style.Font = New Font("tahoma", 14)
NewR.Cells(1).Value = "row Materials Customers"
NewR.Cells(2).Value = ""
NewR.Cells(3).Value = ""
NewR.Cells(4).Value = ""

DGVMezan.Rows.Add(NewR)

I need to add the new row as I have customized it.


Solution

  • Here, you're creating a new DataGridViewRow without a Template:

    Dim NewR As DataGridViewRow = New DataGridViewRow()
    

    The Row is blank and has no concept of columns, so it has no cells.
    If you try to access the empty Cells collection at any index, you get an IndexOutOfRangeException

    You can use the Add() method of the DataGridView's Rows collection to generate a new Row, which is then created with an already defined template, so you can access its Cells collection.

    For example:

    Dim rowIndex = DGVMezan.Rows.Add()
    
    With DGVMezan.Rows(rowIndex).Cells(1)
        .Style.ForeColor = Color.BlueViolet
        .Style.Font = New Font("tahoma", 14)
    End With
    
    DGVMezan.Rows(rowIndex).
        SetValues({"Value1", "row Materials Customers", "Value3", "Value4", "Value5"})
    

    As a note, it's always better having a collection of class objects (or a DataTable), then use this collection as the DataSource of a DataGridView.
    Any data added to or removed from the collection of objects, is immediately reflected in the DataGridView, and the UI is updated.

    If you try to use the DataGridView as a Spreadsheet, you're going to be disappointed