Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a DataTable row to the first position of its DataTable

I want to get a specific row on an asp.net DataTable and move it to be the first one onto this DataTable base on a column column1 value. My Datatable dt1 is populated via a DB query and the value to search is via another query from another DB so I don't know the value to search at the dt1 select time.

// I use this variable to search into
// DataTable
string valueToSearch = "some value";

So I need to search the value some value into my DataTable in the column column1. and then move the entire row to the first position.

Thank you.

like image 201
anmarti Avatar asked Dec 11 '12 17:12

anmarti


2 Answers

We have to clone the row data before:

            DataRow[] dr = dtable.Select("column1 ='" + valueToSearch +"'");
            DataRow newRow = dtable.NewRow();
            // We "clone" the row
            newRow.ItemArray = dr[0].ItemArray;
            // We remove the old and insert the new
            ds.Tables[0].Rows.Remove(dr[0]);
            ds.Tables[0].Rows.InsertAt(newRow, 0);
like image 146
anmarti Avatar answered Sep 24 '22 20:09

anmarti


You will have to test the performance on this, but one way to do this is in the query itself. Get the rows that you want at the top first, and combine that with the rest of the rows.

Since I know nothing of your database, here is a generic way to do this:

SELECT Column1, Column2, Column3
FROM MyTable
WHERE Column1 = 'some value'

UNION

SELECT Column1, Column2, Column3
FROM MyTable
WHERE Column1 <> 'some value'
like image 23
Wonko the Sane Avatar answered Sep 26 '22 20:09

Wonko the Sane