Вопрос

I am using LINQ/C# and trying to return the query's result from a function. What I have is below and does not work. Any suggestions? I know this should go into my Model but one step at a time. When I can get this to work I will then move to model.

Currently my Listbox in the button1_Click is only returning the table names. Example Table1.Table2.

        public IQueryable runDBQuery()
        {

            Variables obj = new Variables();
            var urlList = from SURL in db.SteamURLs
                          where obj.UserID == SURL.uID
                          select SURL;

            dataGridView1.DataSource = urlList;

            return urlList;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var urlList = runDBQuery();

            // This doesn't work?
            listBox1.DataSource = urlList;
        }

ANSWER:

public IList<SteamURL> runDBQuery()
        {

            Variables obj = new Variables();
            var query = from SURL in db.SteamURLs
                          where obj.UserID == SURL.uID
                          select SURL;

            var urlList = query.ToList();
            dataGridView1.DataSource = urlList;

            urlList.ToList();

            return urlList;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var urlList = runDBQuery();

            // This doesn't work?
            listBox1.DataSource = urlList;
            listBox1.DisplayMember = "itemURL";

        }
Это было полезно?

Решение

You are trying to tell the ListBox to be databound to an entire set of fields represented by the SteamURL entity, but the Listbox (which has only a single column that it can display) has no idea which one of the fields to display so it's just showing a default string to represent "an object is bound to this entry in the list".

you need to tell the ListBox what the DisplayMember property is.

e.g if there is a property on a SteamURL called URL (just guessing) then before this line

listBox1.DataSource = urlList;

put this:

listBox1.DisplayMember="URL";

and it should work. I second all the recommendations above by the way, do not return or bind to an IQueryable in this case - you should transform urlList using ToList() or similar first:

var query= from SURL in db.SteamURLs
                         where obj.UserID == SURL.uID
                         select SURL;
//this "materialises" the query and fetches the results back from the database. 
        var urlList= query.ToList(); 
//This means that you won't inadvertently trigger another database access by referring to urlList later on.
       dataGridView1.DataSource = urlList;
       return urlList;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top