PriceCheaperton
PriceCheaperton

Reputation: 5349

checking if gridview is empty using c#

Currently i have the following:

if (dataGridView1.Rows.Count == 0)
{
    MessageBox.Show("EMPTY");
}
else
{
    using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav"))
    {
        soundPlayer.Play(); // can also use soundPlayer.PlaySync()
    }
}

My grid view looks like this:

enter image description here

But it seems to go to the else statement and make the sound. I need it to NOT make a sound if there is no data in the rows of the gridview.

Upvotes: 3

Views: 7583

Answers (3)

RRR
RRR

Reputation: 779

You can use the function GetCellCount() to get the cell count. It requires a parameter called DataGridViewElementStates.Selected

Example:

 if (this.myGridView.GetCellCount(DataGridViewElementStates.Selected) > 0)
        {
            //Do sth
        }
        else
        {
            //Show message
        }

Advantage is you don't need to run database query to check condition using the mentioned function. More details: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.getcellcount

Upvotes: 0

S. S. Rawat
S. S. Rawat

Reputation: 6111

You also check this when populate gridview.. like this

DataSet studentsList = students.GetAllStudents(); 
bool empty = IsEmpty(studentsList); 
if(empty) { 
MessageBox.Show("EMPTY"); 
} 
else { 
using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav"))
{ 
soundPlayer.Play(); 
} 
}

Upvotes: 1

Tigran
Tigran

Reputation: 62246

According to the comment, you have:

dataGridView1.DataSource = BS;

where BS is BindingSource, so you can use its BindingSource.Count property.

So somewhere in the code:

var bindingSource = dataGridView1.DataSource as BindingSource; 
if(bindingSource.Count == 0) {
  MessageBox.Show("EMPTY");
}

Upvotes: 5

Related Questions