Reputation: 567
I have this datatable value with columns cell_1 and cell_2.
I want to check if the value already exist in datatable. I have tried using dt.contain("textbox1.text")
, but it's error because in this datatable doesn't have primary key. Also I have tried using datafilter like this string x = dt_aa.select("cell_1 = textbox1.text")
.
It works well, but when I try to input texbox1.text that doesn't have a value in the column cell_1
. It gives me an error, because it doesn't exist. And my final approach is using this:
For Each dw As DataRow In dt_aa.Rows
If dw("cell_1").ToString() = textbox1.text Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit For
End If
If dw("cell_2").ToString() = textbox2.text Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit For
End If
Next
Is there anyway to simplify it? Because I need to check at least 4 columns with specific value. I am afraid that looping gonna take a while to process (CMIIW). I tried to use LINQ, but I don't quite understand.
Upvotes: 0
Views: 3041
Reputation: 3072
If you want to check if a collection of data has a certain value, you can use Any()
method in Linq.
Linq method syntax (with lambda expression)
Dim foundCell_1 = dt_aa.AsEnumerable.Any(Function (x) x.Field(Of String)("cell_1") = textBox1.Text)
If foundCell_1 Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If Not foundCell_1 Then
Dim foundCell_2 = dt_aa.AsEnumerable.Any(Function(x) x.Field(Of String)("cell_2") = textBox2.Text)
If foundCell_2 Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
Linq query syntax
Dim foundCell_1 = (From rows In dt_aa.AsEnumerable
Where rows.Field(Of String)("cell_1") = textBox1.Text).Any
If foundCell_1 Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If Not foundCell_1 Then
Dim foundCell_2 = (From rows In dt_aa.AsEnumerable
Where rows.Field(Of String)("cell_2") = textBox2.Text).Any
If foundCell_2 Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
If you don't want to use Linq, you can use Select()
method in DataTable
.
Dim foundCell_1 = dt_aa.Select("cell_1 = '" & textBox1.Text & "'").Length > 0
If foundCell_1 Then
XtraMessageBox.Show("Cell_1 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
If Not foundCell_1 Then
Dim foundCell_2 = dt_aa.Select("cell_2 = '" & textBox2.Text & "'").Length > 0
If foundCell_2 Then
XtraMessageBox.Show("Cell_2 already exist !", "", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
The Linq Any()
method might perform faster because it returns true if an element matches the criteria so it doesn't need to check all the data.
Note: I assume both cell_1 and cell_2 are string.
Upvotes: 3