开发者

C#: Select row from DataGridView

I have a form with a DataGridView (of 3 columns) and a Button. Every time the user clicks on a button, I want the get the values stored in the 1st column of that row.

Here is the code I have:

    private void myButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in ProductsGrid.Rows)
        {
            if (this.ProductsGrid.SelectedRows.Count == 1)
            {
             // get information 开发者_Go百科of 1st column from the row
             string value = this.ProductsGrid.SelectedRows[0].Cells[0].ToString();
            }
        }
    }

However when I click on myButton, the this.ProductsGrid.SelectedRows.Count is 0. Also, how do I ensure that the user selects only one row and not multiple rows? Does this code look right?


Set DataGridView.MultiSelect=false and DataGridView.SelectionMode = FullRowSelect. This will make it so the user can only select a single row at a time.


SelectedRows only returns the rows if the entire row is selected (you can turn on RowSelect on the datagridview if you want). The better option is to go with SelectedCells

private void myButton_Click(object sender, EventArgs e)
{
    var cell = this.ProductsGrid.SelectedCells[0];
    var row = this.ProductsGrid.Rows[cell.RowIndex];
    string value = row.Cells[0].Value.ToString();
}


Well, you don't need to both iterate over all rows in your grid and access the collection of SelectedRows. If you skip iteratating and use the SelectedRows collection, then your problem is probably an incorrect SelectionMode:

The SelectionMode property must be set to FullRowSelect or RowHeaderSelect for the SelectedRows property to be populated with selected rows.

(from MSDN)


You can reference the grid similar to an array:

ProductsGrid[ProductsGrid.SelectedColumns[0].Index, ProductsGrid.SelectedRows[0].Index].Value;

By selecting the indexes from the first index of the SelectedRowsCollection and SelectedColumnsCollection you'll grab the first value if multiple rows are selected.


You can lock the user to selecting only a single row by setting the MultiSelect property on the DataGridView. Alternatively you make the CellClick event perform:

ProductsGrid.ClearSelection();
ProductsGrid.Rows[e.RowIndex].Selected = true;


SelectedRows.Count returns the number of entire rows that are currently selected. You probably want to use SelectedCells.Count.


you can also use the .BoundItem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜