728x90

C# SQLite 에서 다중으로 행을 선택한 경우 해당 행을 모두 삭제하는 코드이다.

this.dataGridView1.Rows[this.rowIndex].IsNewRow 은 dataGridVeiw1 에서 새로운 행 추가를 의미하므로 새로운 행 추가가 아닌 경우에만 행을 삭제할 수 있도록 if 문으로 처리했다.

SQLiteDataAdapter adapter;
DataTable ds;
변수 선언은 select 문에서 처리하면서 선언해서 delete 에서는 관련 내용이 나오지 않는다.


if (dataGridView1.SelectionMode != DataGridViewSelectionMode.FullRowSelect)
{
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}

코드도 필요하면 추가해준다.


dataGridView1 자체의 행만 삭제하는 경우에는 아래 코드만 있으면 된다.

foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
    dataGridView1.Rows.RemoveAt(item.Index);
}
하지만 SQLite DB의 테이블 데이터까지 삭제하려면 아래 코드처럼 처리해줘야 한다.


private void btnDelete_Click(object sender, EventArgs e)
{
    if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
    {
        sqliteConn = new SQLiteConnection(ConnectionString);
        sqliteConn.Open();

        foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
        {
            dataGridView1.Rows.RemoveAt(item.Index);
            // Set the DELETE command and parameter.
            adapter.DeleteCommand = new SQLiteCommand(
                "DELETE FROM items "
                + "WHERE uid=@uid;", sqliteConn);
            adapter.DeleteCommand.Parameters.Add("@uid", DbType.Int16, 4, "uid");
            adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
        }

        adapter.Update(ds);
        ds = GetSqliteItems();
        MessageBox.Show("선택한 행이 성공적으로 삭제되었습니다...");
    }
}

블로그 이미지

Link2Me

,