简体   繁体   中英

Check if the data in datagridview is empty or null

I have a problem, probably you guys in this forum could help me.

Here is my problem:

I want to show the MessageBox that say there is no data in datagridview, you cannot delete it. I already can delete the data in the datagridview, but when the datagridview contains 0 data, and i click delete "button", it is error. The error is: Object reference not set to an instance of an object. NullReferenceException Object reference not set to an instance of an object. NullReferenceException

Here is the code that pointed by the error: int rowNum = dataGridView1.CurrentRow.Index;

Here is the code:

private void Delete(object sender, EventArgs e)
{
    DataTable dt = (DataTable) dataGridView1.DataSource;
    int rowNum = dataGridView1.CurrentRow.Index;
    int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]);
    dt.DefaultView[rowNum].Delete();

    using (OleDbConnection conn = new OleDbConnection(connectionString))
    {
        string query = "DELETE FROM [Table] WHERE [ID] = @ID";
        conn.Open();

        using (OleDbCommand cmd = new OleDbCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@ID", id);
            cmd.ExecuteNonQuery();
        }

        if (choice.comboBox1.Text == "English")
        {
            System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
            sound.Play();
            MessageBox.Show("Deleted Successfully!", "Deleted");

            if (rowNum == 0)
            {
                bool rowIsEmpty = true;

                foreach (DataGridViewCell cell in dataGridView1.CurrentRow.Cells)
                {
                    if (cell.Value != null)
                    {
                        rowIsEmpty = false;
                        break;
                    }
                }

                if (rowIsEmpty)
                {
                    System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
                    sounds.Play();
                    MessageBox.Show("Tidak ada Data di Baris ini!", "Error");
                }
                else
                {
                    Delete(sender, e);
                }
            }
        }
    }
}

Does anyone knows how to fix it?

Try like this dt.Rows.count > 0 means that there is data in data table if not there is no data in datatable , if data was present you can do your operation . dt.Rows.count will give the rows count in data table

DataGridView.CurrentRow is usable only when you set DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect . Otherwise you have to get the current row by this:

int rowNum = dataGridView1.CurrentCellAddress.Y;
var currentRow = dataGridView1.Rows[rowNum];

UPDATE

Looks like that you use a DataTable as DataSource for your dataGridView1 , you should take the benefit of Adapter in ADO.NET . This code is just some modifying your current code which in fact updates data in 2 phases: 1. Remove row from DataTable as well as from DataGridView 2. Remove the actual row in database.

    private void Delete(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)dataGridView1.DataSource;
        int rowNum = dataGridView1.CurrentCellAddress.Y;
        if(rowNum == -1) {
           MessageBox.Show("There is no row selected!");
           return;
        }
        int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]);
        //check if row is empty, simply return
        if(IsRowEmpty(rowNum)){
          System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
          sounds.Play();
          MessageBox.Show("There is no data in the selected row", "Error");
          return;
        }
        //Remove the row
        dt.DefaultView[rowNum].Delete();
        dt.AcceptChanges(); //<-- Because you don't use Adapter, call this to restore the row state.
        //Remove the underlying row in database
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            string query = "DELETE FROM [Table] WHERE [ID] = @ID";
            conn.Open();

            using (OleDbCommand cmd = new OleDbCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@ID", id);
                cmd.ExecuteNonQuery();
            }

            if (choice.comboBox1.Text == "English")
            {
                System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
                sound.Play();
                MessageBox.Show("Deleted Successfully!", "Deleted");                    
            }
         }
    }
    //method to check if a row is empty
    private bool IsRowEmpty(int index){
       return dataGridView1.Rows[index].Cells.OfType<DataGridViewCell>()
                                       .All(c=>c.Value == null);
    }

I found the following condition quite useful

if(dataGridView1.DataSource!=null)
{
    // do something
}

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