如何在VB.Net中删除加载时的空白DataGridView行 [英] How to delete blank DataGridView Row on Load in VB.Net
问题描述
我有一个DataGridView,它受VB.net Windows窗体应用程序中的数据源绑定。当我将数据导入DataGrid时,我希望任何空白或空字段都用红色着色,直到用户输入数据。我已经完成了这个,但我有一个小问题。当用户向DataGrid添加一个新的空行并且没有填充任何数据时,加载时新形成的行将完全用红色着色,而我想在加载时删除这个新生成的行。这就是我这样做的方式,但我没有成功。非常感谢您提供的任何帮助或建议。
I have a DataGridView that is bound by a datasource in VB.net Windows forms application. When I import my data into the DataGrid I want any blank or null fields to be colored in red until the user inputs data. I’ve already accomplished this but I have a slight issue. When the user adds a new blank row to the DataGrid and doesn’t fill in any data, that newly formed row on load up will be completely colored in red, instead I want to delete this newly generated row on load. This is how I’ve gone about doing this, but I haven’t been successful. I greatly appreciate any help or suggestions you may offer.
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
‘Created a Boolean flag if empty
Dim empty as Boolean = True
Dim cellString = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If cellString Is Nothing OrElse IsDBNull(cellString) OrElse cellString.ToString = String.Empty OrElse String.IsNullOrWhiteSpace(cellString) = True Then
empty = True
Else
empty = False
End If
End If
‘create variable assigned the rowindex of the last row of the DataGridView
Dim lastRow As String = DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(0).Value
If (e.ColumnIndex = 0 OrElse e.ColumnIndex = 1 OrElse e.ColumnIndex = 2) Then
If empty = False Then
‘If row is not empty then allow the newly generated row on load
DataGridView1.AllowUserToAddRows = true
Else
‘If row is empty and it’s the last row then prevent the row from being added to ‘the datagridview
If empty = True AndAlso e.RowIndex = lastRow Then
DataGridView1.AllowUserToAddRows = False
‘If the row is empty and not the last row then paint the cell red
Else If empty = True AndAlso e.RowIndex <> lastRow Then
DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = Color.Red
End If
End If
End If
End Sub
推荐答案
如果不允许用户添加行,则设置 DataGridView.AllowUserToAddRows [ ^ ]属性为False。我相信这会阻止新行显示在屏幕上。
If the user isn't allowed to add a row, then set the DataGridView.AllowUserToAddRows[^] property to False. I believe this will stop the new row from showing up on the screen.
这篇关于如何在VB.Net中删除加载时的空白DataGridView行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!