如何添加自定义字体颜色与字号的DataGridViewRow并解决索引越界异常?
解决DataGridView添加自定义样式行时的“Index Out Of Range”异常
问题原因
直接通过New DataGridViewRow()实例化的行,没有与目标DataGridView的列集合关联,其Cells集合是空的,因此访问Cells(0)至Cells(4)会触发索引越界异常。
解决方案
提供两种可行的实现方式:
方式一:基于RowTemplate创建匹配列的行
利用DataGridView的RowTemplate克隆行,并创建与列数量匹配的单元格:
' 从DataGridView的行模板克隆新行 Dim NewR As DataGridViewRow = CType(DGVMezan.RowTemplate.Clone(), DataGridViewRow) ' 关键步骤:创建与当前DataGridView列对应的单元格 NewR.CreateCells(DGVMezan) ' 设置单元格内容与样式 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 = "" ' 将配置好的行添加到DataGridView DGVMezan.Rows.Add(NewR)
方式二:先添加空行再配置样式
直接向DataGridView添加空行,获取新行的引用后再设置内容和样式:
' 添加空行并获取行索引 Dim rowIndex As Integer = DGVMezan.Rows.Add() Dim NewR As DataGridViewRow = DGVMezan.Rows(rowIndex) ' 配置单元格内容与样式 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 = ""
内容的提问来源于stack exchange,提问作者Adebo
相关产品推荐
相关产品推荐

