I’ll try to put this as clearly as I can, but I’m all too aware that I may be asking the wrong question. I have a datagrd in WPF (.NET 4.0), which I bind to a datatable in a dataset. The relevant code-behind (running on window load) is:
// create a connection to Top Trumps database
String cs = ConfigurationManager.ConnectionStrings["csTopTrumps"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
// create a new dataset
DataSet ds = new DataSet();
// open the connection (not strictly necessary, as the
// data adapter will do this when you use it anyway)
cn.Open();
// fill data table called Cards with contents of tblCard
SqlDataAdapter daCards = new SqlDataAdapter();
daCards.SelectCommand =
new SqlCommand("SELECT * FROM tblCard ORDER BY CardTitle", cn);
daCards.Fill(ds, "Cards");
// now set the data context for the entire window
this.DataContext = ds;
My datagrid definition begins:
<DataGrid ItemsSource="{Binding Tables[Cards]}"
All of that works fine, and I understand it. I now want to make the data-binding two way, so that changes made in the datagrid will update back to the underlying database. I know that one way I can do this is by getting at the values of changed rows and using a tableadapter with an Update method to write any changes made back to the underlying database (perhaps on something like the SelectedCellsChanged event, or similar). However, any approach like this is difficult to implement, because getting at cell values in code-behind in WPF is difficult (and my understanding is that this is the wrong way to go, as I should be using the WPF framework, so help me).
So … how can I set two-way data-binding to do the work for me? I’ve seen people mention setting datagrid properties like:
SelectedItem="{Binding Path=SelectedIndex,Mode=TwoWay}"
but I don’t understand how I could get this to work with data adapters and datasets. What I don’t want is any solution involving MVVM or models, as I’m not using these (and yes, I probably should be, I know). I also want to avoid reams of complicated C# code, involving observable collections, recursive searches through the control hierarchy to find parents and suchlike.
I’ve searched for a long time, and I THINK what I’m asking does exist – if not, please tell me it doesn’t, and apologies for wasting your time, gentle reader!
OK, a bit late, I think I have the answer I wanted. The datagrid is bound to a data table (in my instance). This means you can get at the selected item (which is the row a user double-clicked on, perhaps), turn it into a datarow and then get at the field you’re interested in.
{
}
This will solve the problem of double-clicking on a row in a datagrid, and is what I had in mind. If you’re using classes, you can cast the selected item into the relevant object, and get at its properties.
I hope this helps someone!