MVS E
MVS E

Reputation: 21

To select Value From Datatable

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 from bool to string

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

Answers (4)

user2064325
user2064325

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

Behzad
Behzad

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

Joel Legaspi Enriquez
Joel Legaspi Enriquez

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

Saragis
Saragis

Reputation: 1792

!= should be part of the string filter you are sending to DataTable.Select but it's also not the correct operator to use. See this link.

Your code should be similar to this:

dt.Select("RollNo <> " & txtRgNo.Text.ToString())

Upvotes: 0

Related Questions