newbie in trouble: binding a mongodb collection to a .net grid

363 views
Skip to first unread message

jmls

unread,
Jun 21, 2012, 12:27:20 PM6/21/12
to mongod...@googlegroups.com
I'm trying to learn c#, visual studio 10 and MongoDB all in one hit. Masochist. 

However, I've created a "book" class, and got my form to connect to Mongo, read all the data, and messagebox it.

What I want to do is to connect by Book collection

using MongoDB.Bson;

namespace WindowsFormsApplication1
{
    class Book
    {
        public ObjectId _id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
    }
}

to a data grid and show the results in there. I can bind the datasource to the book class, but don't know where to go from there. 

I can't seem to create a datasource directly from the collection either.

I know I'm missing something very simple, so please go gentle on my old brain ;)

thanks.

Code for the form is below

public partial class Form1 : Form
    {
        public MongoServer mongo;

        public Form1()
        {
            InitializeComponent();

            mongo = MongoServer.Create();
            mongo.Connect();

            var db = mongo.GetDatabase("tutorial");

            using (mongo.RequestStart(db))
            {
                var collection = db.GetCollection<Book>("books");

                Book newBook = new Book()
                {
                     Author = "Ernest Hemingway",
                     Title = "For Whom The Bell Tolls"
                };

               //collection.Insert(newBook); 

               var query = new QueryDocument("Author", "Ernest Hemingway");
             
               foreach (Book item in collection.Find(query))
               {
                   MessageBox.Show("Author: " + item.Author + " Title:" + item.Title);
               } 
            }
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            mongo.Disconnect();
        }
    }

craiggwilson

unread,
Jun 22, 2012, 8:36:37 AM6/22/12
to mongod...@googlegroups.com
Once you have the collection back from mongodb, then you are in WinForms land.  I'd suggest you use a BindingList<Book> in this example, so something like this:

var bindindList = new BindingList<Book>(collection.Find(query));

gridView.DataSource = bindingList;

Forgive me if I've missed a step here, it's been a while :)

jmls

unread,
Jun 23, 2012, 4:21:37 AM6/23/12
to mongod...@googlegroups.com
Thank you , that sorted the problem. For the record, I was able to use this code

               gridControl1.DataSource = new BindingList<Book>(db.GetCollection<Book>("books").FindAll().ToList());
Reply all
Reply to author
Forward
0 new messages