How to get Devexpress XtraGrid control selected row

devexpressxtragrid

I've a devexpress XtraGrid Control. But, I couldn't get the ID of a by default selected row when the winform loads. I know how to get it when the user clicks on the grid.

Here is the code snapshot:

    private void Form1_Load(object sender, EventArgs e)
    {
     grid1.DataSource = bindData(DataClassesDataContext.Table1.ToList());

     ID = Convert.ToInt32(gridView.GetRowCellValue(gridView.FocusedRowHandle, "ID"));
     XtraMessageBox.Show(ID.ToString());
    }


    public BindingSource bindData(object obj)
    {
        BindingSource ctBinding;
        try
        {
            ctBinding = new BindingSource();

            ctBinding.DataSource = obj;

            return ctBinding;
        }
        catch (Exception ex)
        {
            XtraMessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return null;
        }
    }            

Best Answer

If I understand you correctly, you need something like this:

  private void Form1_Shown(object sender, EventArgs e)
  {
     grid1.DataSource = bindData(DataClassesDataContext.Table1.ToList());

     var item = gridView.GetFocusedRow() as YourDataType
     if(item != null)
     {
       ID = item.ID;
       XtraMessageBox.Show(ID.ToString());
     }
  } 

assuming what your bindData returns a typed collection of some kind.

** Update **

Moving the code to form_Shown seemed to do the trick.

Related Topic