Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert the results of IQueryable to a string to display in a textbox

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!

like image 899
Joe K Avatar asked Feb 15 '23 16:02

Joe K


2 Answers

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?

like image 173
Jon Skeet Avatar answered Feb 19 '23 20:02

Jon Skeet


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

like image 23
Daniele Avatar answered Feb 19 '23 20:02

Daniele