I am trying to add columns dynamically to data grid view using VB.net. But the issue is I need to check that the column name already exists. before adding it if exists I want it to be cancelled automatically. I am using another form to select the Job Nos. which will add as Datagridview Header Text when it saved. () below is the code I am using to add a column to my datagridview. Hope you understand the question. I found some nearby answers in C# unfortunately I am not able to convert those correctly as my C# coding knowledge is little weak.
Thank You!
Dim FRMP = FrmEReview.ReviewGrid.Columns
Dim NOHRS As New DataGridViewTextBoxColumn
FRMP.Add(NOHRS)
NOHRS.HeaderText = Me.Cmb_CName.Text & "-" & Me.Cmb_DName.Text
NOHRS.Width = 160
CodePudding user response:
The obvious option - the one you should have been able to work out for yourself - is to simply loop through the columns and test the HeaderText
of each one:
Dim headerText = $"{Cmb_CName.Text}-{Cmb_DName.Text}"
Dim headerTextFound = False
For Each column As DataGridViewColumn In FrmEReview.ReviewGrid.Columns
If column.HeaderText = headerText Then
headerTextFould = True
Exit For
End If
Next
If Not headerTextFound Then
'...
End If
This is basically the code equivalent of what you'd do manually, which is why you should have been able to do it for yourself, at least mostly.
The not-so-obvious solution for a beginner is to use LINQ. LINQ is basically a means to flatten loops like this, so it leads to far more succinct code:
Dim headerText = $"{Cmb_CName.Text}-{Cmb_DName.Text}"
If FrmEReview.ReviewGrid.
Columns.
Cast(Of DataGridViewColumn)().
All(Function(dgvc) dgvc.HeaderText <> headerText) Then
'...
End If