vb.net - 如何在 GridView 中为网格单元格着色?

标签 vb.net winforms datagrid datagridview

下面是我的代码,我一直在尝试为单元格着色,但不确定当我的网格源是数据库时如何使用“样式”属性。我对此很陌生,所以开始时遇到困难。

一些网站或指针会有很大帮助。

我希望能够为一些背景单元格着色,或者也为一些行或特定列着色......基本上所有与颜色相关的东西。我怎样才能用我当前的代码片段做到这一点?另外,如果我能提供一个可以了解更多信息的链接,我们将不胜感激。

LarsTech 我正在尝试将您添加到聊天中,但我没有足够的代表,因此我想我无法联系您。

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

我收到的错误:

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.    

我尝试过: DataGridView1.Rows(0).Cell(0).Style.BackColor = Color.Red

我得到了 1 个错误:

Error   1   'Cell' is not a member of 'System.Windows.Forms.DataGridViewRow'.   

编辑:在网上查看更多内容后,我使用以下代码为选定的单元格着色:

DataGridView1.Item(4, 5).Style.BackColor = Color.Red

但是,这不会为行或列着色,因此我仍在寻求使这些功能发挥作用。

最佳答案

有几种不同的方法可以做到这一点。我相信当前单元格指的是当前事件单元格,因此填充网格后基于该单元格的着色将不会产生任何结果。

执行此操作的几种方法是:

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

这两者都会将颜色应用于单元格背景。使用一些逻辑来控制如何/哪些单元格/行被着色。

关于vb.net - 如何在 GridView 中为网格单元格着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038354/

相关文章:

c# - 什么是NullReferenceException,如何解决?

c# - C#中的两种不同的窗体

c# - 如何在 datagridview 列中显示总和?

java - 如何将键盘事件添加到数据网格单元格中的文本输入单元格?

c# - "Value Does not fall in the expected range"ClickOnce部署

html - Response.write不显示图像

vb.net - 如何在 VB.NET 中处理 KeyDown

c# - 使用SAME Textbox在dataGridView中搜索和插入数据

c# - 获取数据网格的滚动查看器

c# - WPF DataGrid 无法更改所选行 : stuck on first row