Convert IQueryable Results to String Displayed in Text Box

Using C #, WPF, .NET 4.5 In my program, I am trying to populate a TextBox value from a database. The value is obtained by the LINQ operator. I tried all different things like To.String() and Console.WriteLine() etc. If you can find a way to make this work amazing, if you can find a better way to select the data and display it, I will be interested too. 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!

+4
source share
3 answers

Do you expect one result? If so, use First or Single , or FirstOrDefault to get one Inventory element (which of these options is most appropriate will depend on your situation). However, you will have an Inventory element, and Inventory.ToString() may not give you what you want.

What are you trying to display from inventory? His name? His description? Maybe a combination? You should think about this very carefully - as soon as you decide what you are actually trying to achieve, writing code for it will probably be quite simple.

If your query can return multiple results, you need to think more. Does it make sense to have one text box? Perhaps you should fill out some table?

+4
source

Something like that:

 (from q in inventories where q.InventoryName == name select q).FirstOrDefault().InventoryName; 

You need to also check if FirstOrDefault() null

+3
source

Hi you can try it like

 var result = queryResult.FirstOrDefault(); textBox1.Text=result==null ? string.Empty :result.InventoryName; 

I think it makes no sense to bind if your InventoryName does not start NotifyPropertyChanged, so you better assign text instead of DataContext

+1
source

Source: https://habr.com/ru/post/1495136/


All Articles