Find row in datatable with specific id

2019-01-13 17:48发布

I have two columns in a datatable:

ID, Calls. 

How do I find what the value of Calls is where ID = 5?

5 could be anynumber, its just for example. Each row has a unique ID.

8条回答
对你真心纯属浪费
2楼-- · 2019-01-13 18:17

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.

 public  DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
    {
        TempTable = RecordDT_;
        DataView DV = new DataView(TempTable);
        DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
        return DV.ToTable();
    }

and simply call it as shown below;

  DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

where 5 is the ID. Thanks..

查看更多
老娘就宠你
3楼-- · 2019-01-13 18:19

Make a string criteria to search for, like this:

string searchExpression = "ID = 5"

Then use the .Select() method of the DataTable object, like this:

DataRow[] foundRows = YourDataTable.Select(searchExpression);

Now you can loop through the results, like this:

int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
    // Get value of Calls here
    result = Int32.TryParse(dr["Calls"], out numberOfCalls);

    // Optionally, you can check the result of the attempted try parse here
    // and do something if you wish
    if(result)
    {
        // Try parse to 32-bit integer worked

    }
    else
    {
        // Try parse to 32-bit integer failed

    }
}
查看更多
地球回转人心会变
4楼-- · 2019-01-13 18:19

I could use the following code. Thanks everyone.

int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);
查看更多
姐就是有狂的资本
5楼-- · 2019-01-13 18:27

Try avoiding unnecessary loops and go for this if needed.

string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
    //your logic goes here
}
else
{
    //your logic goes here
}

If you want to search by specific ID then there should be a primary key in a table.

查看更多
你好瞎i
6楼-- · 2019-01-13 18:28

try this code

DataRow foundRow = FinalDt.Rows.Find(Value);

but set at lease one primary key

查看更多
孤傲高冷的网名
7楼-- · 2019-01-13 18:30

You can use LINQ to DataSet/DataTable

var rows = dt.AsEnumerable()
               .Where(r=> r.Field<int>("ID") == 5);

Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

DataRow dr = dt.AsEnumerable()
               .SingleOrDefault(r=> r.Field<int>("ID") == 5);

(Substitute int for the type of your ID field)

查看更多
登录 后发表回答