Tuesday, January 13, 2015

Deleting MongoDB Records using Gridview

So far we have seen select and insert Operations .
we now see how we can perform delete operation.
Place a check box control in the gridview like below



<asp:GridView ID="gvShowTasks" runat="server" CssClass="table table-striped table-bordered table-hover" OnRowCancelingEdit="gvShowTasks_RowCancelingEdit" OnRowEditing="gvShowTasks_RowEditing"  DataKeyNames="Id" OnRowUpdating="gvShowTasks_RowUpdating">
                   <Columns>
                       <asp:TemplateField>
                           <ItemTemplate>
                               <asp:CheckBox ID="chk" runat="server" />
                           </ItemTemplate>
                       </asp:TemplateField>
                       <asp:CommandField ShowEditButton="true" />
                   </Columns>
               </asp:GridView>


on the Code Behind Place the below code in the Delete button click event



protected void btnDelete_Click(object sender, EventArgs e)
    {
        MongoClient monClient = new MongoClient("mongodb://localhost");
        MongoServer ms = monClient.GetServer();
        ms.Connect();
        MongoDatabase db = ms.GetDatabase("testdb");
        MongoCollection collection = db.GetCollection<Tasks>("Tasks");
        Tasks tsk = new Tasks();

        foreach (GridViewRow gvr in gvShowTasks.Rows)
        {
            var rowIndex = gvr.RowIndex;
            var TaskID = gvShowTasks.DataKeys[rowIndex].Values["Id"].ToString();// capturing object id for deletion
            var rowVal = gvShowTasks.Rows[rowIndex].Cells[3].Text;
            CheckBox chk = (CheckBox)gvr.FindControl("chk");
          if (chk.Checked)
          {
              ObjectId bsonId=(ObjectId.Parse(TaskID));//converting string to object id
              IMongoQuery query = Query.EQ("_id", bsonId);
              collection.Remove(query);
             

          }
           
           
        }
        var ShowTasks = collection.FindAllAs<Tasks>().ToList<Tasks>(); //Queries the tasks collection and Converts to List           
        gvShowTasks.DataSource = ShowTasks;//Set the List as Data source 
        gvShowTasks.DataBind();//Binds the Grid
    }

 Run the solution and there you go .. whichever row you have selected , on click of delete button the same row will be deleted . you can also customise your delete query in the statement
  IMongoQuery query = Query.EQ("_id", bsonId);

No comments:

Post a Comment