C# 使用c检查gridview是否为空#

C# 使用c检查gridview是否为空#,c#,.net,winforms,gridview,C#,.net,Winforms,Gridview,目前我有以下几点: 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() } } 我的网格

目前我有以下几点:

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()
    }
}
我的网格视图如下所示:


但它似乎转到else语句并发出声音。如果gridview的行中没有数据,我需要它不要发出声音。

根据注释,您有:

dataGridView1.DataSource = BS;
其中BS是
BindingSource
,因此您可以使用它的属性

所以在代码的某个地方:

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

在填充gridview时也要检查此项。。像这样

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(); 
} 
}

您可以使用函数
GetCellCount()
获取单元格计数。它需要一个名为
DataGridViewElementState的参数。已选择

例如:

 if (this.myGridView.GetCellCount(DataGridViewElementStates.Selected) > 0)
        {
            //Do sth
        }
        else
        {
            //Show message
        }
优点是您不需要使用上述函数运行数据库查询来检查条件。
更多详细信息:

如何使用该网格中的数据填充?
BindingSource BS=new BindingSource();BS.DataSource=dt;dataGridView1.DataSource=BSASP.NET、WPF、Winforms或其他什么?它的数据源是什么?WinForms(Windows应用程序).net 4您在填充gridview时也会检查此项。。像这样的数据集studentsList=students.GetAllStudents();bool empty=IsEmpty(studentsList);如果(空){MessageBox.Show(“空”);}或者{使用(var soundPlayer=new soundPlayer(@“c:\Windows\Media\chimes.wav”){soundPlayer.Play();//也可以使用soundPlayer.PlaySync()}@PriceCheaperton,那么请接受这一正确答案。单击勾号将其变为绿色。@PriceCheaperton谢谢:)让我们在到期的地方给予积分。给那些家伙他们应得的代表:)