How to color Grid cells in Grid View? - vb.net

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:
c#:
For rows/cells:
dataGridView1.Rows[RowNumber].DefaultCellStyle.BackColor = Color.PaleGreen;
dataGridView1.Rows[RowNumber].Cells[1].Style.BackColor = Color.Red;
for columns:
dataGridView1.Columns[ColumnNumber].DefaultCellStyle.BackColor = Color.Black;
VB:
DataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.Green
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.Blue
Both of these will apply color to the cell background. Use some logic in order to control how/which cells/rows are being colored.

You can also set this declaritively in the .aspx file. The link is to a 2.0 version of the code, but this is still compatible.
MSDN

Related

DataGridView DataSource // integer to icon

I've got a list-based application that runs very slow, because each row in my DataGridView is build manually as DataGridViewRow. To fix performance issues i decided to use a DataSource (DataTable) instead.
My problem:
One column I am recieving from my database is filled with image IDs. The application knows which image belongs to which id. When creating gridrows manually there was no problem in translating int to a bitmap and use the bitmap as value for an imagecolumn. Now using the Datatable instead i cant get it working. For testing i wrote the following class:
Public Class test
Dim img As Bitmap
Public Sub New(image As Bitmap)
InitializeComponent()
Me.img = image
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
dt.Columns.Add("StrCol")
dt.Columns.Add("ImgCol")
Dim row As DataRow = dt.NewRow
row.Item(0) = "Ohne Bild"
row.Item(1) = 0
Dim row2 As DataRow = dt.NewRow
row2.Item(0) = "Mit Bild"
row2.Item(1) = 1
dt.Rows.Add(row)
dt.Rows.Add(row2)
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
If e.ColumnIndex = 1 Then
If e.Value = 0 Then
e.Value = Nothing
Else
e.Value = img
End If
End If
End Sub
End Class
hint:
"Ohne Bild" translates into "Without image"
"Mit Bild" translates into "With image"
Output after Button1_Click()
EDIT
Due to a missunderstanding I will try to clarify my question;
By list-based i dont actually mean the list-object. My bad there.By list-based i mean an application that displays the user Database entrys he made. The very basic of my application is simple: Allow user to add Rows, Edit and delete rows in a datagridview. This information is saved and edited in a database. Some of these informations in the rows (2 columns to be exactly) are displayed as icons while the application simply saved an id for the icon in the database. So the application knows which ID belongs to which icon.
The sample dt in the question is just to have something to work with. In the application it will be data recieved from a database to a datatable.
I finally solved it myself.
I get a datatable from my database.
Then I add a Column to it with the DataType Bitmap
Then I loop through each row of the DataTable and translate the Image_ID column to the image itself and put the image into the new Column
Then I remove the Image_ID column
Then I use the new DataTable as DataSource
I created that code in my main application which is a lot more complex so I can't show the code here. Sorry for that and thanks for your help.
It is important to do every change you need to do before using the table as source, because as soon as the gridView has to change something that is displayed it takes a lot more time.

Making a Datatable's content appear in a DataGridView

I am continuing my rewrite of an old VB6 into .Net as part of my .Net learning. I have managed to read a CSV file into a Datatable, and I can view it has populated properly using the 'datatable visualiser' when I look at 'dt', but it doesn't seem to populate the DataGridView control I am trying to tie it to. I have spent a couple of hours browsing other threads and trying things, but I cannot see what I am doing wrong. The DataGridView is on another form in the App, and I am reading the CSV file (a config file of sorts) from the main MDI form. When I show the child form containing the DataGridView it is always empty (it actually seems to have added the two datatable rows, but their content is all blank).
Public dt As New DataTable
Public ThisFilename As String = "c:\SitesDB.cfg"
Private Sub GetSitesDB()
Dim sr As New IO.StreamReader(ThisFilename)
Dim newline() As String = sr.ReadLine.Split(","c)
dt.Columns.AddRange({New DataColumn(newline(0)), New DataColumn(newline(1)), New DataColumn(newline(2)), New DataColumn(newline(3)),
New DataColumn(newline(4)), New DataColumn(newline(5)), New DataColumn(newline(6)), New DataColumn(newline(7)), New DataColumn(newline(8)),
New DataColumn(newline(9)), New DataColumn(newline(10)), New DataColumn(newline(11))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1), newline(2), newline(3), newline(4), newline(5), newline(6), newline(7), newline(8), newline(9), newline(10), newline(11)}
dt.Rows.Add(newrow)
End While
Form1.DataGridView1.DataSource = dt ' data can be seen here using datatable visualiser hovering over 'dt'
End Sub
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
Form1.Show()
End Sub
I have tried refreshing the DataGridView, to no avail. I am wondering if its something to do with Form1.Show() being actioned after the datatable is tied to the DataGridView?
But the following didn't help
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' chkBit.Checked = False
' Dim cfgtext As String : cfgtext = ""
DataGridView1.DataSource = NAMS.dt
End Sub

Autofill TextBox/Checkbox from a previous TextBox' value (VB.NET Database)

Note: I'm using Visual Studio, original work was on SQL Server, moved to VB.NET
I have a Textbox "ViewStatusTxt", next to it there's a Button "ViewStatusBtn"
Below it there's a TextBox "ViewNAMETxt", another TextBox "ViewACTIVITYTxt" and then a Checkbox "ModifyStatusCB"
I'm trying to auto-fill the Checkbox AND the Textbox based on the ID input there, however I really have no clue about it since I'm new to VB.NET
Here's the code used
Private Sub IDSearch(StatusViewBtn As String)
' ADD SEARCH QUERY PARAMETERS - WITH WILDCARDS
SQL.AddParam("#StatusViewBtn", StatusViewBtn)
'RUN QUERY - SEARCH GIVES THOSE RESULTS
SQL.ExecQuery(" SELECT
aID,
Name,
Status,
Activity
FROM
[dbo].[initialTable]
WHERE
aID = #StatusViewBtn
ORDER BY
aID ASC")
End Sub
That's the function's code, which is fully working since it's a smaller version of the same one I used in a Search Page
Here's the button's function, which I'm sure is where I'm having problems, unless I need to add a specific function to the ViewNAMETxt
Private Sub StatusViewBtn_Click(sender As Object, e As EventArgs) Handles StatusViewBtn.Click
IDSearch(StatusViewBtn.Text)
ViewNAMETxt.Text = SQL.ExecQuery("SELECT
Name
FROM
initialTable
WHERE
aID = #StatusViewBtn")
End Sub
And I haven't even started on the Checkbox, viewing how the first one caused me issues. Hopefully the solution would be similar to both of them.
Thanks for reading guys, and sorry for the newbie question
1- Suppose you have a table named YourTable(int KeyColumn, string StringColumn, boolean BooleanColumn)
2- Create a form and put 2 textboxes and a checkbox and a button on it. KeyColumnTextBox, StringColumnTextBox, BooelanColumnCheckBox, SearchButton
3- In click event handler for SearchButton put the codes:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim connection = New SqlConnection("Your Connection string here")
Dim command = New SqlCommand("SELECT StringColumn, BooleanColumn FROM YourTable WHERE KeyColumn=#KeyColumn", connection)
command.Parameters.Add(New SqlParameter("#KeyColumn", Int32.Parse(KeyColumnTextBox.Text)))
connection.Open()
Dim reader = command.ExecuteReader()
While reader.Read()
StringColumnTextBox.Text = reader.GetString(0)
BooleanColumnCheckBox.Checked = reader.GetBoolean(1)
End While
End Sub
Don't forget to Imports System.Data.SqlClient at top of your file.

Refresh/Requery combobox on form after record saved on separate form

I have spent all morning googling and looking through this site and just haven't found anything that seems to work. I have a combobox on form1 that gets its display values from a datasource tblCardTypeDD. Its Display Member is sCardType and its value member is iCardTypeID. Its selected member is fkCardTypeID from tblInventory.
When I click a button form2 pops up with a simple datagridview that allows me to add more card types to be used in the drop down. Currently I have been trying to add code to the save button click method but I just can't find a combination that actually updates the combobox.
I have been trying the following:
frmInventory.SEquipTypeComboBox.DataSource = Nothing
frmInventory.SEquipTypeComboBox.DataSource = Me.EngDBbeDataSet.tblCardTypeDD
but the drop down becomes blank after execution of the above.
Any help would be appreciated.
You should check this page, maybe it'll help you:
http://msdn.microsoft.com/en-us/library/w67sdsex.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
In case it didn't:
if you put your breakpoint where you "reset" The combobox Datasource binding, Check if the datasource contains the new values you want to see in your combobox. it might sound stupid but its a mistake that often happens, if this is the case you know that the problem isn't with the binding
Also after making the datasource nothing and adding the datasource again in the way you did you should tell which column will be the displaymember again like so:
ComboBox1.DisplayMember = "Column1"
Though if you look at the site I told you about you should look at the note that tells you how to suspend and resume binding instead of dropping the datasource and adding it again like that.
Though if you're using a datatable the values should automatically change, and there should be no reason to drop and rebind the combobox.
--
To prove that you don't need to rebind i've very quickly made a very dirty piece of code to prove it.
form1 has a combobox that's bound to a datatable, and it also has a button to call a second form named form2.
form2 has a button that adds 2 rows to the Datatable and then goes back to the first screen.
Code Form 1:
Public Class Form1
Private dataSet As New DataSet("DataSet1")
Private dataTable As DataTable = dataSet.Tables.Add("DataTable1")
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
dataTable.Columns.Add("Column1")
Dim row1 As DataRow = dataTable.NewRow()
row1("Column1") = "Data1"
dataTable.Rows.Add(row1)
Dim row2 As DataRow = dataTable.NewRow()
row2("Column1") = "Data2"
dataTable.Rows.Add(row2)
ComboBox1.DataSource = dataTable
ComboBox1.DisplayMember = "Column1"
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim form2 As New Form2(dataTable)
form2.Show()
End Sub
End Class
Code Form2:
Public Class Form2
Private _dataTable As DataTable
Public Sub New(ByVal dataTable As DataTable)
InitializeComponent()
_dataTable = dataTable
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim row3 As DataRow = _dataTable.NewRow()
row3("Column1") = "Data3"
_dataTable.Rows.Add(row3)
Dim row4 As DataRow = _dataTable.NewRow()
row4("Column1") = "Data4"
_dataTable.Rows.Add(row4)
Me.Close()
End Sub
End Class

apparent bug when repopulating a datagridview

I have a created a simple example to illustrate what I have found. I also have a "fix", but I don't think I should need it!
I am using VS2010 and .NET 4. My form has a DataGridView (dgvTest), and a checkbox (CheckBox1). I am selecting 2 or 3 fields from a table, depending on whether the checkbox is checked (which it is initially).
My possible SQL statements are "SELECT ID,strForenames,strSurname FROM tblAlumni" and "SELECT strForenames,strSurname FROM tblAlumni".
I have used SQL Profiler to confirm that these are the queries sent to the DB.
All seems well when I load the form (I see 3 fields, in the order I expect), and when I uncheck the box (I see 2 fields, in the order I expect).
However, when I check it again, the ID field appears THIRD in the columns of the DataGridView, not first!
I have found a couple of reports of something similar to this (mis)behaviour on the Net, but folks just seem to find some other way to do the job rather than ask is this a problem with DataGridView that needs fixed.
Since I have been able to recreate it with a simple example I have some confidence (only some!) that I am not missing anything obvious.
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System
Public Class Form1
Inherits System.Windows.Forms.Form
Dim sqlConn As SqlConnection
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
loadGRID()
End Sub
Private Sub loadGRID()
Dim sqlConn As SqlConnection = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=aspnetdb;Integrated Security=True")
sqlConn.Open()
Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter("SELECT " & IIf(CheckBox1.Checked, "ID,", "") & "strForenames,strSurname FROM tblAlumni", sqlConn)
Dim ds As DataSet = New DataSet()
dataAdapter.Fill(ds)
dgvTest.DataSource = ds.Tables(0)
sqlConn.Close()
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
loadGRID()
End Sub
End Class
So my question is, do your experts agree this is a bug? The "fix" is to wipe the DataGridView between repopulations, but I'm not sure I should have to?
dgvTest.DataSource = Nothing
dgvTest.Refresh()
I have found a BindingSource as a glue between the 'datasource' and the datagridview works very nicely for me, sorry I know that doesn't answer whether this is a bug as I am not sure.
(c#)
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = ds.Tables(0);
bindingSource.ResetBindings(false);
However, when I check it again, the ID field appears THIRD in the columns of the DataGridView, not first!
Thats the expected behaviour as the columns strForenames and strSurname already exist.
Try dgvTest.Columns.Clear() before and dgvTest.refresh after changing the datasource