I have a table "Cards" in a database with tables "Cards" and "Customers". Cards contains CustomerID, Number and Ammount. After that, I used ADO.NET to make use of DataGrid
, TextBox
, etc.
I dropped a DataGrid
and a TextBox
as a Search Criteria. When a button is pressed, the DataGrid
is loaded with the LINQ:
string searchString = this.CustomerIDTextBox.Text();
using (var ctx = new bdCustomerEntities()){
var result = from t in ctx.Cards
join t_customer in ctx.Customer on t.CustomerID equals t_customer.id
where t.CustomerID == searchString
select new
{
number = t.number,
ammount = t.ammount,
CustomerID = t.Customer.id
};
/*Fill datagrid*/
this.CardsDataGrid.ItemsSource = result.ToList();
}
The problem comes when I made a MouseDoubleClick
event in the CardsDataGrid
to select the row and fill two TextBox
es, one with the Ammount data and the other one with Number.
I tried this code but it fails to show the data in the TextBox
es:
Cards selected = this.cardsDataGrid.SelectedItem as Cards;
this.numberTextBox.Text = selected.Number.ToString();
this.ammountTextBox.Text = seleccionado.Ammount.ToString();
I made a MessageBox.Show
after the Cards selected = ...
line to see the content on the SelectedItem
, and it shows something like this:
{number = 13, ammount = 3500 , CustomerID = 1456 }
My problem is that, I can't "extract" the SelectedItem
because of the format created - maybe by the LINQ? - and put that in the TextBox
es.
Something I noticed, when I made this change to the above code:
Cards selected = (Cards) this.cardsDataGrid.SelectedItem ;
It shows:
System.InvalidCastException:Unable to cast object of type '[System.Int32,System.Int32,System.String]' to type 'bdCustomer.Cards'.
Your LINK is returning an anonymous type not the Cards
type, and there is no cast available between the anonymous type and the Cards
type, which is what the error is telling you.
Change your LINQ to this:
var result = from t in ctx.Cards
join t_customer in ctx.Customer on t.CustomerID equals t_customer.id
where t.CustomerID == searchString
select t;