select an item in a DataGridView

0

very good, I'm trying to select an element of a DataGridView, however, I can not get the selected item because the 'SelectedItem' function does not appear the following code

private void myData_SelectionChanged(object sender, EventArgs e)
    {
        DataGrid data = sender as DataGrid;
        DataRowView view = myData.SelectedItem as DataRowView;
    }

the screenshot

    
asked by Matthew Seidel 19.10.2018 в 22:50
source

2 answers

2

There is no such property, because you do not try to use

DataGridView.SelectedRows Property

along with the property

DataGridViewRow.DataBoundItem Property

something like being

private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
   foreach(var row in DataGridView1.SelectedRows){
        var view = ((DataRowView)row.DataBoundItem).Row
        //resto codigo
   }
}

If you are only going to allow a single selection, remember to remember

DataGridView.MultiSelect Property

then you could use

private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
   if(DataGridView1.SelectedRows.Count == 0){
      return;
   }

   var row = DataGridView1.SelectedRows[0];
   var view = ((DataRowView)row.DataBoundItem).Row

   //resto codigo

}
    
answered by 19.10.2018 / 23:08
source
1

Try the following:

private void myData_SelectionChanged(object sender, EventArgs e)
    {
       if (myData.SelectedRows.Count > 0)
            {
                DataGridViewRow dr = myData.SelectedRows[0]; 

            }
    }

Clarification: Here you are not selecting a row. You are only getting the one that is currently selected.

To select a row you should do something like this:

this.grid.Rows[int index].Selected = true;
    
answered by 19.10.2018 в 23:05