Reputation: 21
In the below code I have a datatable
I want to select a value from datatable
and to check whether value exists or not, but it throws error:
The best overloaded method match for
System.Data.DataTable.Select(string)
has some invalid argument "," cannot convert frombool
tostring
Please help me to solve the issue.
Student Details = new Student ();
DataSet ds = Details.Marks();
DataTable dt = ds.Tables[0];
if (dt.Select("RollNo =" != txtRgNo.Text.ToString()) ||
dt.Select("Name=" != txtName.Text.ToString()))
{
}
else
{
}
Upvotes: 0
Views: 604
Reputation: 21
Student Details = new Student ();
DataSet ds = Details.Marks();
DataTable dt = ds.Tables[0];
DataRow dr1=dt.Select("RollNo!= " + txtRgNo.Text.ToString());
DataRow dr2=dt.Select("Name !="+ txtName.Text.ToString())
if (dr1.Length>0 ||dr2.Length>0 )
{
}
else
{
}
Upvotes: 1
Reputation: 3590
You can use the Linq Queries to select and filter any fields like this:
Student Details = new Student();
DataSet ds = Details.Marks();
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
var result = from d in dt.AsEnumerable()
where d["RollNo"].ToString() == txtRgNo.Text &&
d["Name"].ToString() == txtName.Text
select new
{
RollNo = d.Field<int>("RollNo"),
Name = d.Field<string>("Name")
};
if (result.Any())
{
// results is not empty ...
}
}
Upvotes: 0
Reputation: 1236
The DataTable's "Select()" method uses a filter expression. As a sample you can use the following to query for specific RollNo, and it returns DataRow array. If DataRow returns more than one elements, then it exists. Otherwise, it does not exist.
int rollNumber = 1;
string filterExpression = string.Format("RollNo = {0}", rollNumber);
DataRow[] rows = dt.Select(filterExpression);
if (rows != null && rows.Length > 0)
{
//Exists
}
else
{
//Does not exists
}
A complete filter expression in your case would be like:
string filterExpression = string.Format("RollNo <> {0} AND Name <> '{1}'", txtRgNo.Text.ToString(), txtName.Text.ToString());
Additional reference to use DataTable.Select(): https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx
Upvotes: 0