Using C#, WPF, .NET 4.5
In my program, I am trying to populate the value of a TextBox from a database. The value is obtained by a LINQ statement. I've tried all different things such as To.String()
and Console.WriteLine()
etc. If you can figure out a way to make this work that would be awesome, if you can find a better way to select the data and display it, i would be interested in that as well.
C# Code:
private AuroraEntities auroraContext = null;
private void LoadTB()
{
this.auroraContext = new AuroraEntities();
ObjectQuery<Inventory> inventories = auroraContext.Inventories;
string name = ingNameCB.SelectedValue.ToString();
var queryResult = (from q in inventories
where q.InventoryName == name
select q);
textBox1.DataContext = queryResult.ToString();
}
XAML:
<TextBox Height="23" HorizontalAlignment="Left" Margin="70,186,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=InventoryName, Mode=TwoWay}"
thanks!
Are you expecting a single result? If so, use First
, or Single
, or FirstOrDefault
to obtain a single Inventory
item (which of these options is most appropriate will depend on your situation). However, you will then have an Inventory
item, an Inventory.ToString()
may well not give you what you want either.
What are you trying to display from the inventory? Its name? Its description? Perhaps a combination? You should think about that very carefully - once you've decided what you're actually trying to achieve, writing the code for it is likely to be quite simple.
If your query could return multiple results, you've got even more to think about. Does it even make sense to have a single textbox? Perhaps you should be populating a table of some kind?
Something like this:
(from q in inventories
where q.InventoryName == name
select q).FirstOrDefault().InventoryName;
You need also to check if FirstOrDefault()
is not null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With