我有一个DataGridView(3列)和一个按钮的窗体。每次用户点击一个按钮时,我都希望获取存储在该行第一列中的值。C#:从DataGridView中选择行
这里是我的代码:
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in ProductsGrid.Rows)
{
if (this.ProductsGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string value = this.ProductsGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
然而,当我点击为myButton的this.ProductsGrid.SelectedRows.Count为0。另,我怎么确保用户只选择一个行不是多行? 此代码是否正确?
你并不需要遍历(的foreach)在DataGrid的所有行只得到第一个SelectedRow。 foreach循环在这里浪费时间。 – 2010-04-29 22:11:30