0

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;
        }
    }            
aby
  • 810
  • 6
  • 21
  • 36
  • What is the type in `Table1` ? – Jens Kloster Apr 03 '13 at 09:43
  • it's a table object that is accessed using LINQ to SQL – aby Apr 03 '13 at 11:06
  • Could you specify the problem you are having. I don't think I understand what you need. – Jens Kloster Apr 03 '13 at 11:20
  • The problem is that every time the form loads it throws "Object reference not set to an instance of an object." When i look deeper into the code, the problem lies on getting the focused row (by default) value. It returns 0 (for the ID) even though there are too many rows in the list. It works fine when i click on the rows though. But, what I want it to get the ID when the form loads – aby Apr 03 '13 at 11:37
  • you should really add that to your question. If it returns 0, you are looking at the `RowHandle`, not the row value. Try moving your code to a `form_Shown` event instad of `form_Load` event – Jens Kloster Apr 03 '13 at 11:42
  • Super! I'll update my answer, so that you can mark it correct. thank you – Jens Kloster Apr 03 '13 at 12:31

1 Answers1

0

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.

Jens Kloster
  • 11,099
  • 5
  • 40
  • 54