dcsimg
Results 1 to 26 of 26

Thread: How do I use a listboxes selected value as a LINQ qry parameter?

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    How do I use a listboxes selected value as a LINQ qry parameter?

    Hi everyone,

    I want to update my data grid when the user makes a selection:

    Code:
    private void SiteNameListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                loadgrid();
            }
    How do I change the 0 in my where clause to a listboxes selection?
    I thought
    Code:
    where d.Site_id > SiteNameListBox.SelectedValue
    would work but I was wrong. Here is my entire statement
    Code:
    private void loadgrid()
            {
                ProductivityEntities PE = new ProductivityEntities();
                var data = from d in PE.pt_COGS
                           //from s in PE.pt_Site
                           where d.Site_id > 0
                           select d;
                dataGridView1.ItemsSource = data.ToList();
            }
    Thank you,

    -Justin

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    'd.Site_id' is type 'int', right? What's the data type of 'SiteNameListBox.SelectedValue'? That should give you a clue.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Correct it is an int. The error I'm getting is:

    Operator'=='cannot be applied to operands of type 'int' and object

    heres is the xmal:
    Code:
            <ListBox x:Name="SiteNameListBox" ItemsSource="{Binding}" SelectionChanged="SiteNameListBox_SelectionChanged">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock  x:Name="SiteID" Margin="5,0"  Text="{Binding IDSite}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
    I was binding two TextBlocks in the list box originally. Now just one, which in my database it's an int as well. Is it because a listbox has to be a string?

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    [QUOTE=justair07;5330923Is it because a listbox has to be a string?[/QUOTE]
    Um, no. A ListBox is a ListBox. It has to be a ListBox because that's what it is.
    Quote Originally Posted by justair07 View Post
    Operator'=='cannot be applied to operands of type 'int' and object
    So the '==' operator can't be used to compare an Object and an 'int'. If you want to compare an 'int' to something else, what do you suppose it would need to be? Another 'int' maybe? So... if you have an Object reference but the underlying value is an 'int', what do you do?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Um, no. A ListBox is a ListBox. It has to be a ListBox because that's what it is.
    Sorry I meant, values in a list box, are they converted to string?
    if you have an Object reference but the underlying value is an 'int', what do you do?
    Declare the object as an int? I tried this but still didnt work:
    Code:
            private void loadgrid()
            {
                ProductivityEntities PE = new ProductivityEntities();
                var SelListBoxItem = SiteNameListBox.Items.Cast<int>();
                var data = from d in PE.pt_COGS
    
                           //from s in PE.pt_Site
                           where d.Site_id == SelListBoxItem
                           select d;
                dataGridView1.ItemsSource = data.ToList();
            }
    Operator'=='cannot be applied to operands of type 'int' and 'IEnumerable<int>'

    Am I getting closer?

  6. #6

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Name:  Capture.jpg
Views: 24
Size:  36.9 KB
    This didn't work either

  7. #7
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Read the error message:
    are you missing a cast?
    Yes, you are. You need to cast that Object reference as type 'int' if you want to use it where an 'int' is required. You can't compare an Object to an 'int' and you can't assign an Object to an 'int' variable. You need to cast it, which is telling the compiler that you are taking responsibility for ensuring that the underlying value actually is an 'int' at run-time.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    40,280

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Quote Originally Posted by justair07 View Post
    var SelListBoxItem = SiteNameListBox.Items.Cast<int>();
    SelListBoxItem is a singular name (has no S on the end), so it seems rather odd that you are trying to assign all items from the list to it.


    Try something like this:
    Code:
                var SelListBoxItem = (int)SiteNameListBox.SelectedValue;

  9. #9

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Quote Originally Posted by jmcilhinney View Post
    Read the error message:

    Yes, you are. You need to cast that Object reference as type 'int' if you want to use it where an 'int' is required. You can't compare an Object to an 'int' and you can't assign an Object to an 'int' variable. You need to cast it, which is telling the compiler that you are taking responsibility for ensuring that the underlying value actually is an 'int' at run-time.
    I tried to cast on my first attempt in post #5. It didn't work.

  10. #10

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Quote Originally Posted by si_the_geek View Post
    SelListBoxItem is a singular name (has no S on the end), so it seems rather odd that you are trying to assign all items from the list to it.


    Try something like this:
    Code:
                var SelListBoxItem = (int)SiteNameListBox.SelectedValue;
    Hi si,

    I tried as you suggested and here is what i got:
    Attached Images Attached Images  

  11. #11
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Then that means that the SelectedValue of that ListBox does not contain an 'int'. Like I said:
    ou need to cast it, which is telling the compiler that you are taking responsibility for ensuring that the underlying value actually is an 'int' at run-time.
    There's no point telling the compiler that and then not actually taking that responsibility. Why are you trying to use the SelectedValue as an 'int' in the first place if it isn't one? What is it?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    It is an int. See picture. Is it being converted to text here:
    Code:
    <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock  x:Name="SiteID" Margin="5,0"  Text="{Binding IDSite}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
    ughhh the picture keeps attaching sideways, here is the code:
    Code:
    private void loadlist()
            {
                var context = new ProductivityEntities();
    
                var site = context.pt_Site.First();
    
                // SiteCodeTextBlock.Text = site.SiteCode;
    
                var q = from s in context.pt_Site
                        where s.IDSite > 0
                        orderby s.IDSite
                        //select new { s.SiteName, s.IDSite };
                        select new { s.IDSite };
    
                SiteNameListBox.DataContext = q.ToList();
            }
    and class

    Code:
    public partial class pt_Site
        {
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public pt_Site()
            {
                this.pt_COGS = new HashSet<pt_COGS>();
                this.pt_ProjectsSites = new HashSet<pt_ProjectsSites>();
            }
        
            public int IDSite { get; set; }
            public string SiteCode { get; set; }
            public string SiteName { get; set; }
        
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<pt_COGS> pt_COGS { get; set; }
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<pt_ProjectsSites> pt_ProjectsSites { get; set; }
        }
    Attached Images Attached Images  
    Last edited by justair07; Nov 6th, 2018 at 07:47 PM.

  13. #13
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Quote Originally Posted by justair07 View Post
    It is an int.
    No it isn't. If it was then casting it as that type would be working. Your picture is useless as it doesn't provide any information about that SelectedValue. Instead of telling us what you think it should be, try looking to see what it actually is. Use the debugger. That's what it's there for. When the exception is thrown, look at the SelectedValue in the debugger and see what its actual value is. My guess is that it is null but we shouldn't have to guess when you have the code running in the debugger right in front of you.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    I'm confused because you can see in my function I'm referencing IDSite from Class pt_Site. You can see in the class that IDSite is indeed an int. Here is what the debugger shows: <Anonymous Type>???

    It's like it goes into the listbox as an int and comes out as an Anonymous Type
    Attached Images Attached Images  
    Last edited by justair07; Nov 6th, 2018 at 08:15 PM.

  15. #15
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Quote Originally Posted by justair07 View Post
    It's like it goes into the listbox as an int and comes out as an Anonymous Type
    Nope. It comes out as exactly the same thing as it goes in as. This:
    Code:
                var q = from s in context.pt_Site
                        where s.IDSite > 0
                        orderby s.IDSite
                        //select new { s.SiteName, s.IDSite };
                        select new { s.IDSite };
    is specifically creating a new object with a property named IDSite. That is how you create an anonymous type: with the 'new' keyword followed by a property list in braces. If you just want the 'int' values themselves then just select the 'int' values:
    Code:
                var q = from s in context.pt_Site
                        where s.IDSite > 0
                        orderby s.IDSite
                        select s.IDSite;
    That code is selecting an 'int' value from each item instead of an instance of an anonymous type with an 'int' property.

    I didn't actually pick that up from post #12 because I didn't realise what code was populating the ListBox and what code was using the selection. That's why you should ALWAYS provide a FULL and CLEAR description. If you're posting the code that populates a ListBox then say that, rather than just posting a code snippet and assuming that people will work out what it is. I'm sure I'm not alone in not always having a lot of time when I'm looking at questions here so the less time I have to spend working out what's what, the better for both of us.
    Last edited by jmcilhinney; Nov 6th, 2018 at 09:46 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Thank you so much! I will do a better job at pointing out what code is what going forward.

    The code seems to be "working". When I click from item to item, the grid changes. Something funny going on though. The first picture is what my form looks like before I made the fix you gave me. You can see the IDSite in the list box (1, 2). Granted when I click on them the grid does not change. The 2nd and 3rd pictures show what the form looks like now. No values in the list box but when I toggle from section to section, the grid changes as I would expect.

    How do I bring the values back? Or even better, since IDSite is a PK and doesn't mean anything to the user, what if I wanted to show SiteName which is another element in the same class as IDSite?

    Here is my XAML code for the binding in the listbox:
    Code:
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock  x:Name="SiteID" Margin="5,0"  Text="{Binding IDSite}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
    Attached Images Attached Images    
    Last edited by justair07; Nov 6th, 2018 at 09:02 PM.

  17. #17
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    In WinForms, you can bind a list of simple values or complex objects to a ListBox. The WPF ListBox will bind a list of complex objects too but perhaps not a list of simple values. In that case, you would need to go back to selecting an anonymous type and bind that, but then also set the DisplayMemberPath and SelectedValuePath properties. If you bind a list of objects of an anonymous type with a property named IDSite, you can set the DisplayMemberPath to IDSite and then the values of that property will be displayed in the control and you can also set the SelectedValuePath to IDSite and then the values of that property are what will be returned by the SelectedValue property. It seems like your best option is to go back to this:
    Code:
                var q = from s in context.pt_Site
                        where s.IDSite > 0
                        orderby s.IDSite
                        select new { s.IDSite };
    and set the DisplayMemberPath and SelectedValuePath properties to IDSite.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  18. #18

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    It sounds like WinForms are easier to work with than WPF?

  19. #19
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    40,280

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    In some circumstances (like this one) WPF is a bit harder, and in others it is easier... and with WPF you have more functionality built-in (which is much easier, if you want that functionality).

    The extra work in this situation is setting a couple of properties (which only takes a few seconds), and a minor amendment to the code (which is shown above).

  20. #20
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,383

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Quote Originally Posted by justair07 View Post
    It sounds like WinForms are easier to work with than WPF?
    Yes, but WPF does offer various things that WinForms struggles to do or just can't.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  21. #21

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    I would much rather stick with the WPF but I can't figure out how to do this:
    and set the DisplayMemberPath and SelectedValuePath properties to IDSite.

  22. #22
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    40,280

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    What have you tried?

    In case it helps, here are some examples of setting properties:
    Quote Originally Posted by justair07 View Post
    Code:
                            <TextBlock  x:Name="SiteID" Margin="5,0"  Text="{Binding IDSite}" />
    Code:
                SiteNameListBox.DataContext = q.ToList();
    Code:
                this.pt_COGS = new HashSet<pt_COGS>();
                this.pt_ProjectsSites = new HashSet<pt_ProjectsSites>();

  23. #23

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Here is what I tried.
    Code to load the grid:
    Code:
            private void loadgrid()
            {
                ProductivityEntities PE = new ProductivityEntities();
                var SelListBoxItem = SiteNameListBox.SelectedValuePath.Cast<int>();
                var data = from d in PE.pt_COGS
    
                           //from s in PE.pt_Site
                           where d.Site_id > SelListBoxItem
                           select d;
                dataGridView1.ItemsSource = data.ToList();
            }
    Code to load the listbox:
    Code:
            private void loadlist()
            {
                var context = new ProductivityEntities();
    
                var site = context.pt_Site.First();
    
                // SiteCodeTextBlock.Text = site.SiteCode;
    
                var q = from s in context.pt_Site
                        where s.IDSite > 0
                        orderby s.IDSite
                        select new { s.IDSite };
    
                SiteNameListBox.DisplayMemberPath = q.ToList();
            }
    Here is a screen shot of where I'm getting the errors
    Attached Images Attached Images  

  24. #24
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    40,280

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    You were told to set the properties (ie: give them a value), not read from them... so reading SelectedValuePath isn't the right thing to do.

    You were also told to set them both to IDSite, but instead you set DisplayMemberPath to a list of items (and removed the DataContext, so there is no longer any data to display).


    DataContext specifies the list of items.
    DisplayMemberPath specifies which property of those items to display.
    SelectedValuePath specifies which property of those items to return when you read SelectedValue.

  25. #25

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    I just can't figure out how to do this
    Code:
    You were told to set the properties (ie: give them a value)
    or this
    Code:
    You were also told to set them both to IDSite

  26. #26

    Thread Starter
    Member
    Join Date
    Jun 2018
    Posts
    47

    Re: How do I use a listboxes selected value as a LINQ qry parameter?

    Got it! Thank you!
    Code:
    <ListBox x:Name="SiteNameListBox" ItemsSource="{Binding}" 
                     DisplayMemberPath="SiteName" SelectedValuePath="IDSite" 
                     SelectionChanged="SiteNameListBox_SelectionChanged"/>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width