使用C#检查GridView是否为空

3

目前我有以下内容:

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

我的网格视图如下所示:

enter image description here

但似乎它会进入else语句并发出声音。如果网格视图的行中没有数据,我希望它不发出声音。


你怎么填充那个网格的数据? - Tigran
BindingSource BS = new BindingSource(); BS.DataSource = dt; dataGridView1.DataSource = BS; - PriceCheaperton
ASP.NET、WPF、Winforms或其他什麼?它的數據源是什麼? - Tim Schmelter
WinForms(Windows 应用程序).Net 4 - PriceCheaperton
当填充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(); // can also use soundPlayer.PlaySync() } } - S. S. Rawat
您的DataGridView具有索引为NewRowIndex的1行。DataGridView.Rows集合中的DataGridViewRow对象数量并不总是等于基础DataSource中的对象数量。 - Arie
3个回答

5

根据评论,您有:

dataGridView1.DataSource = BS;

这里的BS是指BindingSource,您可以使用它的BindingSource.Count属性。

因此,在代码的某个地方:

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

@PriceCheaperton,请接受这个作为正确答案。点击勾选以将其变为绿色。 - uriDium
1
@PriceCheaperton 谢谢 :) 让我们给应得的信誉。给那些家伙应有的声望 :) - uriDium

1
你也可以在填充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(); 
} 
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接