Change DataGridView last row Color using C# and VB.Net in Windows Application

Last Reply one year ago By dharmendr

Posted one year ago

Hi! I have datagridview with data. When I run it the changed end cell color background.

For example: if row = 15 then end row (15) backgrouncolor changed by green.

if row = 10 then end row (10) backgrouncolor changed by green.

Posted one year ago

Hi PRA,

Check this example. Now please take its reference and correct your code.

Code

C#

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        BindDataGrid();
    }

    private void BindDataGrid()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { 
                    new DataColumn("Id", typeof(int)),
                    new DataColumn("Name", typeof(string)),
                    new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        this.dataGridView1.DataSource = dt;
        this.dataGridView1.AllowUserToAddRows = false;
        this.dataGridView1.AutoResizeColumns();
        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            if (row.Index == dt.Rows.Count - 1)
            {
                row.DefaultCellStyle.BackColor = Color.Green;
            }
        }
    }
}

VB.Net

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        BindDataGrid()
    End Sub

    Private Sub BindDataGrid()
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn() {
                            New DataColumn("Id", GetType(Integer)),
                            New DataColumn("Name", GetType(String)),
                            New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        Me.dataGridView1.DataSource = dt
        Me.dataGridView1.AllowUserToAddRows = False
        Me.dataGridView1.AutoResizeColumns()
        For Each row As DataGridViewRow In Me.dataGridView1.Rows
            If row.Index = dt.Rows.Count - 1 Then
                row.DefaultCellStyle.BackColor = Color.Green
            End If
        Next
    End Sub
End Class

Screenshot