views:

1870

answers:

3

I'm engaged in a C# learning process and it is going well so far. I however just now hit my first "say what?" moment.

The DataTable offers random row access to its Rows collection, not only through typical collections behavior, but also through DataTable.Select. However I cannot seem to be able to tie this ability to DataRow.Delete. So far this is what it seems I need to do in order to conditionally delete one or more rows from a table.

int max = someDataTable.Rows.Count - 1;
for(int i = max; i >= 0; --i)
{
    if((int)someDataTable.Rows[i].ItemArray[0] == someValue)
    {
        someDataTable.Rows[i].BeginEdit();
        someDataTable.Rows[i].Delete();
    }
    else
        break;
}
someDataTable.AcceptChanges();

But I'm not happy with this code. Neither I'm convinced. I must be missing something. Am I really forced to hit the Rows collection sequentially if I need to delete one or more rows conditionally?

(don't mind the inverted for. I'm deleting from the end of the datatable. So it's ok)

+6  A: 

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}
Matthew Whited
Ah! Didn't occur to me Select() would return a reference to the datatable rows. I knew I had to be missing something. Thanks a bunch!
Krugar
+2  A: 

I don't have a windows box handy to try this but I think you can use a DataView and do something like so:

DataView view = new DataView(ds.Tables["MyTable"]);
view.RowFilter = "MyValue = 42"; // MyValue here is a column name

// Delete these rows.
foreach (DataRowView row in view)
{
  row.Delete();
}

I haven't tested this, though. You might give it a try.

itsmatt
I tried and it worked. I do prefer the Select approach though. But good thing to keep in mind. Thanks :) +1
Krugar
A: 
if(isset($_POST['delete']))
{$query = "select * from emp_detail";
$result = mysql_query($query) or die(mysql_error());
while ($r = mysql_fetch_row($result)){
    //foreach ($r as $key => $value)
    //{
    //echo "$key: $value<br/>";
$e_id = $r['e_id'];
//for($i=0;$i<count($_POST['checkbox']);$i++){
//$del_id = $_POST['delete'];
if(isset($_POST['e_id']))
{
$e_id = $_POST['e_id'];
$query = "delete from emp_detail where e_id ='$e_id' " ;
$result = mysql_query($query) or die(mysql_error());
}//}
$query= "select username,email,address from emp_detail";
$result = mysql_query($query) or die(mysql_error());
}
}
brijal
this is gibberish. Format your code
Krugar