Click here to Skip to main content
15,920,383 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello:

I am trying to use a datagrid column to select records to delete. I worked it out on C#, but I need help working it on VB.

Here is my code:
C#
List<int> rowsToDelete = new List<int>();
using (SqlConnection conn = new SqlConnection("connString"))
{
    using (SqlCommand cmd = new SqlCommand())
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell checkBox = dataGridView1[0, row.Index] as DataGridViewCheckBoxCell;
            if (checkBox != null) //checking if correct row is checkboxcell
            {
                if (Convert.ToBoolean(checkBox.Value) == true)//checking if tick is added
                {
                    //deleting from DB:
                    cmd.CommandText = @"DELETE FROM Stock WHERE ID = @myID";
                    cmd.Parameters.Add("@myID", SqlDbType.Int).Value = Convert.ToInt32(dataGridView1[1, row.Index].Value.ToString());
                    cmd.ExecuteNonQuery(); //deleting current row from db

                    //deleting from DGV (now adding into a list, and deleting it afterwards):
                    rowsToDelete.Add(row.Index);
                }
            }
        }
    }
}

//deleting rows from DGV:
foreach (int row in rowsToDelete)
    dataGridView1.Rows.RemoveAt(row);

Is there an equivalent to VB?
Posted
Updated 14-Jan-14 16:18pm
v2

Using an online translation tool ...

VB
Dim rowsToDelete As List(Of Integer) = New List(Of Integer)
Imports (
Dim conn As SqlConnection = New SqlConnection("connString")
If (Not (checkBox) Is Nothing) Then
    If (Convert.ToBoolean(checkBox.Value) = true) Then
        'deleting from DB:
        cmd.CommandText = "DELETE FROM Stock WHERE ID = @myID"
        cmd.Parameters.Add("@myID", SqlDbType.Int).Value = Convert.ToInt32(dataGridView1(1, row.Index).Value.ToString)
        cmd.ExecuteNonQuery
        'deleting current row from db
        'deleting from DGV (now adding into a list, and deleting it afterwards):
        rowsToDelete.Add(row.Index)
    End If
End If
UnknownUnknownUnknown'deleting rows from DGV:
For Each row As Integer In rowsToDelete
    dataGridView1.Rows.RemoveAt(row)
Next
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900