locked
Insert a "Select User" row in Linq for a dropdown list RRS feed

  • Question

  • User1827130465 posted

    I'm new to Linq. I have searched and searched the web for a soluion, and can't find anything. I have a Linq query and I want to insert a row ("Select User") to the top before I pass it to the drop down list. I've been trying to use the Union but to now avail (it keeps telling me that my object doesn't support the Union method). My code, prior to attempting to inser a row, is very simple.

    public SelectList DropDown_Users()
            {
                var context = new VivarianDataContext();
                var query = from t in context.AspnetUsers
                            select new { t.UserId, t.LastName };

                list = new SelectList(query.AsEnumerable(), "UserId", "LastName");
                return list;
            }


    Now I try to insert a row and I found this on the internet and it seems to say that his solution will work. But it is filled with syntax errors. http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-method-and-linq/


    I tried to implement it using the following code, but it doesn't compile.

    public SelectList DropDown_Users()

            {
                SelectList list;

                //get the original data          
               var context = new SQL2005633131VivarianDataContext();
               var query = from t in context.AspnetUsers

                select new { t.UserId, t.LastName };

                //create a dummy table with an empty row
                var AllUsers = new List<AspnetUsers>();
                var BlankUser = new AspnetUsers()
                    {UserId=System.Guid.Empty, LastName="Select One"};
                AllUsers.Add(BlankUser);   

                //use Union to join the data - ERRORS HERE
               var newTable = AllUsers.Union(query);


                list = new SelectList(newTable.AsEnumerable(), "UserId", "LastName");
                return list;
            }


    So tired I'm going blind. Any help?


    Thanks

    Monday, September 6, 2010 10:47 PM

Answers

  • User1224194097 posted

    Sorry my bad. Insert is a void method and it inserts an item at specified position. Does not return anything. Please try this way

    <title>Snippet</title>

    public object GetUsers()
        {
            //get the original data          
            var context = new SQL2005633131VivarianDataContext();
            var results = (from t in context.AspnetUsers
                           select new
                           {
                               t.UserId,
                               t.LastName
                           }).ToList();
            //Add new Item
            results.Insert(0,
     new
                    {
                        UserId = System.Guid.Empty,
                        LastName = "Select One"
                    });
            return results.ToList();
        }

    May be you need to change the function return type depending on the result, but I am assuming that Object should work.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 7, 2010 12:56 AM

All replies

  • User1224194097 posted

    I have a Linq query and I want to insert a row ("Select User") to the top before

    you can return the list of AspNetUsers from your function with new item added on top. Set DataTextField and DataValueField of the DropDownList to LastName and UserID respectively. you can do something like this

    <title>Snippet</title>

    public List<AspNetUsers> GetUsers()
    {
        //get the original data          
        var context = new SQL2005633131VivarianDataContext();
        return (from t in context.AspnetUsers
                        select new
                        {
                            t.UserId,
                            t.LastName
                }).ToList().
                Insert(0, new AspnetUsers()
                {
                    UserId = System.Guid.Empty,
                    LastName = "Select One"
                });
    }

    Call that funtion and it should return the list of Users. Try that and see if it works.

    Monday, September 6, 2010 11:44 PM
  • User1827130465 posted

    Thansk for the reply Santosh. Unfortunately, there is a syntax error.

    Insert(0, new AspnetUsers()

    gives two errors "Cannot convert AspnetUsers to AnonymousType#1.

    and "Cannot convert void to System.Generic.Collections.List<>"

    To resolve this I delete the AspnetUsers() so that it creates an anonymous object. This made the first error go away.

    But the second error is due to the Insert() method returning void and I can't figure out how to resolve this.


    Thanks,


    Brian



    Tuesday, September 7, 2010 12:47 AM
  • User1224194097 posted

    Sorry my bad. Insert is a void method and it inserts an item at specified position. Does not return anything. Please try this way

    <title>Snippet</title>

    public object GetUsers()
        {
            //get the original data          
            var context = new SQL2005633131VivarianDataContext();
            var results = (from t in context.AspnetUsers
                           select new
                           {
                               t.UserId,
                               t.LastName
                           }).ToList();
            //Add new Item
            results.Insert(0,
     new
                    {
                        UserId = System.Guid.Empty,
                        LastName = "Select One"
                    });
            return results.ToList();
        }

    May be you need to change the function return type depending on the result, but I am assuming that Object should work.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 7, 2010 12:56 AM
  • User1827130465 posted

    Wow, we are getting close! There is one last error on the return statement.

    Cannot implicity convert ...Generic.List<AnonymousType#1> to ... AspnetUsers

    So I changed it to

    return (List<AspnetUsers>)results;

    and this gives the error "Cannot conver type.... <AnonymousType#1> to... AspnetUsers



    Tuesday, September 7, 2010 1:29 AM
  • User1224194097 posted

    Can you post the function which returns the list and the code where that function is being called.

    I think there is a mismatch in the function return type and I am assuming that my view is different from how you are loading the dropDownList.

    Tuesday, September 7, 2010 1:38 AM
  • User1827130465 posted

    It works! I'm incredibly, extremely, remarkably happy right now.  

    I was writing you a reponse and I was looking at the problem. The function is returning a list a AspnetUsers and it won't let me convert to/from a List. But as I'm trying to figure out how to make it do this, I realize that I don't have to do this. If you look at my original post, all I need to return is a SelectedList object. So I took your code that showed me how to insert a new item into the list, and used that instead. The ToList() method is compatible with SelectedList! What a relief!!!


    Here is my code:


    public SelectList DropDown_Users()
            {
                var context = new SQL2005633131VivarianDataContext();
                var query = (from t in context.AspnetUsers
                            select new { t.UserId, t.LastName }).ToList();
                query.Insert(0, new { UserId = System.Guid.Empty, LastName = "Select One" });
                var list = new SelectList(query, "UserId", "LastName");
                return list;
            }


    Thanks so much! I can go to sleep now.  Laughing





    Tuesday, September 7, 2010 2:17 AM
  • User1827130465 posted

    I'll mark you last response as the answer since it was a combination of multiple posts.


    Tuesday, September 7, 2010 2:18 AM
  • User-1903939959 posted

     

    Use the AppendDataBoundItems property of the DropDownList.  This property allows you to append addtional data bound items like a Linq query result or datatable to whatever you specify as a listitem in the control.  So I added a blank list item and added the linq query to the data source.

     

    private void LoadSponsors()

        {

       ScreeningLinqToSQLDataContext scrctx = new ScreeningLinqToSQLDataContext();

        var query = from sponsors in scrctx.tblSponsors

        orderby sponsors.SponsorName

        where sponsors.SponsorName != ""

        select sponsors;          

      ddlSponsor.DataSource = query;

      ddlSponsor.DataBind();

    }

    http://www.hybridcoder.com/Home/EntryId/5/Add-Blank-Link-to-DropDownList-Loaded-by-Linq-Query.aspx

     

    Monday, May 9, 2011 5:23 AM