Wednesday, March 2, 2011

C#.NET - Rebind DataGridView Control after User Deleted Row

// Datagridview control is binded with DataSource.
// Deleting a row from DatagridView control and hence from DataBase,

private void DataGridView_KeyDown(View sender, KeyEventArgs e)
        {
            if (e.KeyValue == 46)
            {
                if (DataGridView.SelectedRows.Count > 0)
                {
                    if (MessageBox.Show("Are you sure you want to Delete  Record?", "Complaint Details", MessageBoxButtons.YesNo, MessageBoxIcon.Warning).ToString().ToLower() == "yes")
                    {
                        nIndex = DataGridView.SelectedRows[0].Index;
                        DeleteRow(nIndex);
                    }          
                }
            }
        }

// DeleteROw is user defined function, delete the record from database.

    private void DeleteRow(int nIndex)
        {
            int nDeleted;
            BusinessLayer oBusinessLayer = new BusinessLayer();

            nDeleted = oBusinessLayer.DeleteRecord("(" + DataGridView.Rows[nIndex].Cells["colID"].Value.ToString() + ")");
            if (nDeleted != 0)
            {
                MessageBox.Show("Record(s) can not be Deleted.", "Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Record(s) Successfully Deleted.", "Databse", MessageBoxButtons.OK, MessageBoxIcon.Information);

        // Rebind the datasource with updated Databse
          
        Dtg_ComplaintDetails.DataSource = oDataTable;
                LoadDataGrid(oDataTable);            
            }
        }


No comments:

Post a Comment