Ryan
Ryan

Reputation: 672

searching a datatable

I am trying to get a "fuzzy" search working on a datagridview that is bound to a DataTable.

I am trying to use DataTable.Select but I don't see it working. Here is my code:

private void buttonSearch_Click(object sender, EventArgs e)
{
   string SearchString;

   if (this.textSearchString.Text == "")
   {
      return;
   }

   SearchString = this.textSearchString.Text;

   DataRow[] rows = dt.Select("PartName Like '" + SearchString + "%'");

   dt.Rows.Clear();
   foreach (DataRow row in rows)
   {
      dt.Rows.Add(row.ItemArray);
   }
   this.datagridInventory.DataSource = null;
   LoadInventoryList(); //loads up dt and formats columns
}

I am not sure if this is right and it does not seem to work. Can someone point out my errors or explain the concept better to me?

Upvotes: 0

Views: 1856

Answers (3)

user3136434
user3136434

Reputation: 1

StringBuilder searchQuery = new StringBuilder();

foreach (DataColumn column in dataTable.Columns)
{
  if (string.IsNullOrEmpty(searchQuery.ToString()))
    searchQuery.Append(column.ColumnName + " like '%" + searchString + "%' ");
  else
    searchQuery.Append(" OR " + column.ColumnName + " like '%" + searchString + "%' ");
}

DataRow[] foundRows = dataTable.Select(searchQuery.ToString());

if (foundRows != null && foundRows.Length > 0)
{
  dataTable = new DataTable();
  dataTable = foundRows.CopyToDataTable();
}

Now the dataTable having search result.

Upvotes: 0

Daniel Szabo
Daniel Szabo

Reputation: 7281

Try removing your dt.Rows.Clear(); command. It deletes all the rows in your datatable.

However, if you want to preserve both sets of data (your orginal dataset and your selected rows), you'll need to dt.clone() the table you're searching into a new datatable (.clone simply creates a new datatable with the same structure as the first, without copying the data), and then dump the results of your query into the new table with clonedTable.Rows.ImportRow().

DataTable clonedTable = dt.Clone();

DataRow[] rows = dt.Select("PartName Like '" + SearchString + "%'");

foreach ( DataRow row in rows ){
    cloneTable.importRow( row );
}

clonedTable.acceptChanges();

Upvotes: 1

lboshuizen
lboshuizen

Reputation: 2786

You are iterating through a set of datarows that you clear (=made empty) before you iterate.

Remove dt.Rows.Clear();

Then you are adding items from the "dt" to the same "dt"??

First of all this makes no sense as there are no more rows after the clear() Second, if you remove the clear then there is no longer use to iterate over them and add them again.

Upvotes: 1

Related Questions