views:

298

answers:

1

I'm trying to write a simple Compact Framework winforms app. The main form has a DataGrid bound to a DataTable (with data from an xml file). I want to bring up another form that displays the details of the current record. I have something like the following code as the constructor for the detail form.

public DetailsForm(DataTable dtLandlords, int Index) //the constructor
{
  InitializeComponent();
  lLandlordCode.DataBindings.Add("Text", dtLandlords, "LandlordID");
  .......
}

I'm Calling the constructor with the following code

    Form frm = new LandlordDetailsForm(dtLandlords, dataGrid1.CurrentRowIndex);
    frm.Show();

How do I get it to display the current record (specified in Index - currently not used) rather than just the first record. Or is there a better way that I should be doing this?

+1  A: 

Databindings "bind" to a provided "View", currently you are binding to the DataTable without setting the default view (So it will default to the complete table). Eg. dtLandlords.DefaultView.RowFilter = "LandlordID = TheIdYouWant";

The other way to do it is to add the DataGrid/GridView itself to the DataBingings which will provide a default view containing it's currently selected item.

Edit: Added example of binding to a DataGridView

An example of this is: First create a form with a TextBox and DataGridView (default names). Then put this code in the constructor of the form.

DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
DataRow dr;
dr = dt.NewRow();
dr[0] = "C1R1";
dr[1] = "C2R1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "C1R2";
dr[1] = "C2R2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "C1R3";
dr[1] = "C2R3";
dt.Rows.Add(dr);

this.dataGridView1.DataSource = dt;
this.textBox1.DataBindings.Add("Text", dataGridView1.DataSource, "Col1");

Then run, and select items in the GridView and the TextBox should automagically be updated with the selected details. Note: I used a DataGridView here, I assume it will also work for DataGrids (which I think you are using)

Tetraneutron
Your first suggestion works, thanks. However I'd like to know more about your second suggestions about adding the DataGrid to the DataBindings
Alister
I edited the main answer with an example of how to do this. If this was the accepted answer can you mark it as such? I believe by clicking the tick under the answers rating, Cheers.
Tetraneutron