I am using MongoDB with C# driver. I managed to add/delete/update data from collections, but I dont know how to display a collection in the gridview. If it's not possible, how can I display collections as tables in asp.net?
First load a query from mongodb like this:
var server = MongoServer.Create("mongodb://localhost:27020");
var database = server.GetDatabase("someDb");
var collection = database.GetCollection<User>("someCollection");
var searchQuery = Query.EQ("someName", "someValue"); // you can place any search condition here
//if you want all documents from collection use FindAll
var cursor = collection.Find(searchQuery);
cursor.SetLimit(50); // you can specify limit
// set sort orders
cursor.SetSortOrder(SortBy.Ascending("someSorField").Descending("someSorField2"));
var resultList = cursor.ToList(); //get list of items from mongodb
Then on Page_Load event, bind data:
gvwExample.DataSource = resultList;
gvwExample.DataBind();
Then specify binding to datasource on the page:
<asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" CssClass="basix" >
<columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
</columns>
</asp:GridView>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With