SalarianEngineer
SalarianEngineer

Reputation: 636

Search C# DataTable for List of terms, then return row Id for the results

I'm new to using DataTables and am confused about why this does not work.

What I want to do is search the "text" column of all rows in the DataTable for any of the words listed in the "terms" (List). If one of them is found, I want to add the Id of the row to another list, "resultIds" (List).

The three columns for the DataTable are created from a SQL result that has the following columns:

Can someone assist me with understanding why this doesn't work?

The error is "Error 4 Argument 1: cannot convert from 'object' to 'int'".

Edit: Now I'm getting an "Object reference not set to an instance of an object error" when it tries to add the Id to the list.

    public ActionResult Search(MyModel model)
    {
        // This string gets passed in as part of the Model from the View
        string delimitedText = model.text.Replace(" ", ",");

        // Convert the comma delimited string into a List<>.
        List<string> terms = delimitedText.Split(',').ToList();

        // List<> to hold all Ids for matched DataTable rows
        List<int> resultIds = null;

        // Populate the DataTable with SQL result set
        DataTable dt = TableDAO.Search();

        // For each term in the "terms" List<>
        foreach (string term in terms)
        {
            // Search each DataRow in the DataTable
            foreach (DataRow dr in dt.Rows)
            {
                // If the DataRow's column "text" contains the current term in the "terms" List<>...
                if (dr["text"].ToString().Contains(term))
                {

                    // Error: "Object reference not set to an instance of an object", happens with resultIds.Add((int)dr["id"]); as well.
                    resultIds.Add((int)dr.ItemArray[0]);
                }
            }
        }

        return RedirectToAction("Index", resultIds);
    }

Upvotes: 0

Views: 943

Answers (1)

Feras Salim
Feras Salim

Reputation: 438

resultIds.Add(dr["id"]) is a dynamic expression and in the compile time it considered as object so you have to convert it as follows

resultIds.Add(int.Parse(dr["id"].ToString()));

Upvotes: 2

Related Questions