
网友skypaf 的原问题发表在csdn的bbs上:http://bbs.csdn.net/topics/392271272
我个人的理解是他想让新增的一行与原来的行样式不一致。
那么如何在datagrIDvIEw中完成呢?
说实在的以往写代码的时候还真没有这么考虑过这样的问题,
先说看到问题后自己走的一个弯路:
下图中红框标出的部分,
这一行虽然是空白的,但是它的的确确是,datagrIDvIEw的最后一行,用代码就是:
datagrIDvIEw.Rows(datagrIDvIEw.Rows.Count - 1)
我在那里将新增的一行的前景色、字体设置了半天不显示,就是以为有内容的才是最后一行,哪里知道这个自动生成的行才是真正的最后一行。
因此,如果需要避免这个问题,请把 DataGrIDVIEw.AllowUserToAddRows 属性设置为False。
那么代码还是比较容易的:
Private Sub btnAdd_Click(sender As Object,e As EventArgs) Handles btnAdd.Click Call addStudent() Call setRowStyle() End Sub Private Sub addStudent() Dim studentname As String = txtname.Text Dim studentID As String = txtID.Text Dim studentAge As String = txtAge.Text Dim student() As String ReDim student(2) student(0) = studentname student(1) = studentID student(2) = studentAge dgvStudent.Rows.Add(student) End Sub Private Sub setRowStyle() Dim defaultStyle As New DataGrIDVIEwCellStyle defaultStyle.Font = New Font("宋体",12) defaultStyle.Forecolor = color.Blue Dim newRowStyle As New DataGrIDVIEwCellStyle newRowStyle.Font = New Font("黑体",12) newRowStyle.Forecolor = color.Red If dgvStudent.Rows.Count > 1 Then dgvStudent.Rows(dgvStudent.Rows.Count - 2).DefaultCellStyle = defaultStyle dgvStudent.Rows(dgvStudent.Rows.Count - 1).DefaultCellStyle = newRowStyle Else dgvStudent.Rows(dgvStudent.Rows.Count - 1).DefaultCellStyle = newRowStyle End If End Sub 显示效果如下: 另外一个注意的地方是:
代码最后一个判断语句,我开始的时候使用的是:
If dgvStudent.Rows.Count > 0 Then dgvStudent.DefaultCellStyle = defaultStyle dgvStudent.Rows(dgvStudent.Rows.Count - 1).DefaultCellStyle = newRowStyle End If想法是,每次增加都是表格所有先使用defaultStyle,然后使新增加的行,也就是最后一行样式变为newRowStyle。 但是结果却不是我想象的: 也就是说,dgvStudent.DefaultCellStyle = defaultStyle 没有发挥作用,推测是因为设置了单个行的defaultcellStyle,所有表格总体样式就对已经设置的行不起作用了。 那只能枚举每一行修改样式:
Private Sub button2_Click(sender As Object,e As EventArgs) Handles button2.Click Dim newRowStyle As New DataGrIDVIEwCellStyle newRowStyle.Font = New Font("黑体",12) newRowStyle.Forecolor = color.Blue dgvStudent.DefaultCellStyle = newRowStyle For Each singlerow As DataGrIDVIEwRow In dgvStudent.Rows singlerow.DefaultCellStyle = newRowStyle Next End Sub 由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录
总结以上是内存溢出为你收集整理的datagridview中使最新增加的一行样式不一样 兼谈网友 skypaf 的问题全部内容,希望文章能够帮你解决datagridview中使最新增加的一行样式不一样 兼谈网友 skypaf 的问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)