DataGridView中的选定行始终为0

Kao*_*oru 3 c# datagridview

如果所选行为0,我想显示消息"您没有选择任何行".

但是,即使我单击datagridview中的第一行,我跟踪它,所选行总是给我0.

为什么会那样?

这是代码:

MessageBox.Show(dataGridView1.SelectedRows.Count.ToString()); // below function always run, because the selected rows always 0, even i clicked the first row in datagridview (when run the program)

if (dataGridView1.SelectedRows.Count == 0)
{
    if (choice.comboBox1.Text == "English")
    {
        System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
        sound.Play();
        MessageBox.Show("You Have Not Selected Any Rows!", "Error");
    }
}

else
{
    DeleteDatabase(sender, e);
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 6

MSDN说

SelectionMode属性必须设置为FullRowSelect或RowHeaderSelect,以便使用选定的行填充SelectedRows属性.

您需要相应地设置此属性,否则不需要SelectedRows.