简体   繁体   中英

Delete a row by condition from DataTable

I created DataTable in my project.Fill it with table in database.

Dim myDataTable As New DataTable(Table_Name)

Dim myLocalConnection As New SqlConnection(_ConnectionString)
myLocalConnection.Open()

Dim mySqlDataAdapter As New SqlDataAdapter()
myCommand.Connection = myLocalConnection
mySqlDataAdapter.SelectCommand = myCommand
mySqlDataAdapter.Fill(myDataTable)

Now i want to delete a specific row from tableby condition. And update the table on database. with SqlDataAdapter.Update() method.

mySqlDataAdapter.Update(myDataTable)

How could i do this? help...

Use something like

foreach (DataRow row in myDataTable.Rows)
    if (row ...) // implement your condition here
        myDataTable.Rows.Remove(row);

C# code here because you ask for C# in your title.

You have to provide the DeleteCommand of the DataAdapter . Then you can use DataRow.Delete to change it's row-state to RowState.Deleted which causes the dataadapter to delete it from database when you use DataAdapter.Update(myDataTable) .

To find the rows that you want to delete you can use Linq-To-DataSet :

Dim deleteCommand = new SqlCommand("DELETE FROM ...", myLocalConnection)
mySqlDataAdapter.DeleteCommand = deleteCommand 

Dim query = From row In myDataTable
            Where row.Field(Of String)("ColumnName") = "Delete-Condition"
For Each row As DataRow in query 
    row.Delete()
Next

mySqlDataAdapter.Update(myDataTable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM