I have a vb.net program that has a datagridview and a button where end users are to paste data from excel to the grid using the button. The user copies data from excel and click the paste button in program to paste the data in datagridview. I only want the user to be able to paste 50 records in the datagridview. The issue I am having is the end users can copy over 50 rows and paste in the grid. It will display a message box that "The max number of rows is 50" but the grid will have all the rows from the excel copy to display in the grid. How do I set the paste to show the first 50 rows and remove the others how do I set the datagridview to only display 50 records?
Here is the copy I am using:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnPaste.Click
btnClear.Enabled = True
Dim maxRowCount As Integer
maxRowCount = 51
Try
For Each line As String In Clipboard.GetText.Split(vbNewLine)
If Not line.Trim.ToString = "" Then
Dim item() As String = line.Trim.Split(vbTab)
Me.gridUserEntries.Rows.Add(item)
End If
Next
If gridUserEntries.Rows.Count > maxRowCount Then
MsgBox("The max number of rows are 50")
'gridUserEntries.RowsRemoved()
'gridUserEntries.AllowUserToAddRows = False
' gridUserEntries.Rows.Remove(gridUserEntries.RowCount)
btnValidate.Enabled = False
Else
btnValidate.Enabled = True
btnRetrieve.Enabled = True
'gridUserEntries.Rows.Remove(row)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
I have tried to gridUserEntries.AllowUserToAddRows = False
I am expecting to be able to paste more than 50 record but only display the first 50 rows in the datagridview.
CodePudding user response:
Change:
For Each line As String In Clipboard.GetText.Split(vbNewLine)
To:
For Each line As String In Clipboard.GetText.Split(vbNewLine).Where(Function(s) Not String.IsNullOrWhiteSpace(s)).Select(Function(s) s.Trim()).Take(50)