Below is my code and I have been trying to color the cells but not sure how to use the “Style” property when my source for grid is a DB. I am new to this so having difficulties getting started.
Some website or pointers would help a lot.
I want to be able to color some background cells or also color some rows or specific columns…Basically everything color related. How can I do this with my current snippet? Also a link to where I can learn more would be appreciated.
LarsTech I am trying to add you to a chat but I dont have enough rep so I think I can’t contact you due to that.
Imports System.Data.SqlClient
Imports System.Collections.Generic
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = "data source=SQst; database=MVar2; User ID=Wepp; Password=2010Live; Integrated Security=false;"
Dim sql As String = "SELECT * FROM Prer"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
**DataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.PaleGreen
DataGridView1.Rows[3].Cells[1].Style.BackColor = Color.Red**
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Call PrintDGV.Print_DataGridView(DataGridView1)
End Sub
End Class
Errors I get:
Error 1 Property access must assign to the property or use its value.
Error 2 Identifier expected.
Error 3 Property access must assign to the property or use its value.
Error 4 Identifier expected.
I tried:
DataGridView1.Rows(0).Cell(0).Style.BackColor = Color.Red
and I got 1 error:
Error 1 'Cell' is not a member of 'System.Windows.Forms.DataGridViewRow'.
EDIT: After looking more around the web I got to color selected cells using below code:
DataGridView1.Item(4, 5).Style.BackColor = Color.Red
This however doesn’t color rows or columns so I am still looking to make those things work.
There are a few different ways of doing this. I beliebe that currentcell refers to the current active cell, so coloring based on that after filling your grid will yield no results.
A few ways to do this are:
Both of these will apply color to the cell background. Use some logic in order to control how/which cells/rows are being colored.