Tuesday, December 10, 2013

Checkbox function for gridview and delete function

Creating checkbox for gridview together with delete function

In this tutorial, I'll be using a book management system as an example.



NOTE: In this tutorial, I used a shortcut to connect the connection string. You can still use your normal connection string. However, if you wish to use the shortcut, remember to replace your connectionStrings line in your Web.config

 TO BE REPLACED IN WEB.CONFIG

 <connectionStrings>  
   <add name="ApplicationServices"  
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"  
      providerName="System.Data.SqlClient" />  
   
   <add name="connString" connectionString="data source=_______________;database=_________________________;Integrated Security=True" providerName="System.Data.SqlClient"/>  
  </connectionStrings>  
   

Firstly, insert this javascript below which activates the checkbox.

 <script type="text/javascript">  
   var TotalChkBx;  
   var Counter;  
   window.onload = function () {  
     //Get total no. of CheckBoxes inside the GridView.  
     TotalChkBx = parseInt('<%= this.grdData.Rows.Count %>');  
     //Get total no. of checked CheckBoxes in side the GridView.  
     Counter = 0;  
   }  
   function HeaderClick(CheckBox) {  
     //Get target base & child control.  
     var TargetBaseControl =  
     document.getElementById('<%= this.grdData.ClientID %>');  
     var TargetChildControl = "selectbookchklist";  
     //Get all the control of the type INPUT in the base control.  
     var Inputs = TargetBaseControl.getElementsByTagName("input");  
     //Checked/Unchecked all the checkBoxes in side the GridView.  
     for (var n = 0; n < Inputs.length; ++n)  
       if (Inputs[n].type == 'checkbox' &&  
         Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)  
         Inputs[n].checked = CheckBox.checked;  
     //Reset Counter  
     Counter = CheckBox.checked ? TotalChkBx : 0;  
   }  
   function ChildClick(CheckBox, HCheckBox) {  
     //get target control.  
     var HeaderCheckBox = document.getElementById(HCheckBox);  
     //Modifiy Counter;   
     if (CheckBox.checked && Counter < TotalChkBx)  
       Counter++;  
     else if (Counter > 0)  
       Counter--;  
     //Change state of the header CheckBox.  
     if (Counter < TotalChkBx)  
       HeaderCheckBox.checked = false;  
     else if (Counter == TotalChkBx)  
       HeaderCheckBox.checked = true;  
   }  
 </script>  

Next, within your gridview and before the 1st boundfield.

 <asp:TemplateField HeaderText="Select">  
   <HeaderTemplate>  
   <asp:CheckBox runat="server" ID="selectallbookchklist" onclick="javascript:HeaderClick(this);"/>  
   </HeaderTemplate>  
   <ItemTemplate>  
     <asp:CheckBox ID="selectbookchklist" runat="server" />  
   </ItemTemplate>  
   </asp:TemplateField>  

Lastly, insert the delete button.
(You can ignore this part if you are not implementing the delete function using checkbox)

 <asp:Button ID="delbtn" Text="Delete" Width="70px" runat="server"   
       onclick="delbtn_Click"/>  

Now, you are done for the basic presentation of checkbox and delete button. Next part will be implementing the code behind file.

In this tutorial, the delete function does not literally delete the record. It hides the records in database by creating an attribute named RecordDeleteDate, type=datetime, Allow null.

If a record is deleted, the delete button updates the RecordDeleteDate with the date. Hence, when the web browser calls out for all records, the records with RecordDeleteDate filled up will not be displayed. However, the record can be viewed if the web browser calls out for deleted records.

 protected void delbtn_Click(object sender, EventArgs e)  
     {  
       int numofRecordsDeleted = 0;  
       CheckBox deleteCheckBox;  
       CBookManager BooksManager = new CBookManager();  
       foreach (GridViewRow row in grdData.Rows)  
       {  
         deleteCheckBox = (CheckBox)row.FindControl("selectbookchklist");  
         if (deleteCheckBox.Checked == true)  
         {  
           numofRecordsDeleted += BooksManager.deleteOneBook(grdData.DataKeys[row.RowIndex].Value.ToString());  
         }  
       }  
       divMessage.InnerHtml = numofRecordsDeleted.ToString() + " book record(s) has been deleted";  
       DataTable BookDataTable = new DataTable();  
       BookDataTable = BooksManager.getAllBookData();  
       grdData.DataSource = BookDataTable;  
       grdData.DataBind();  
     }  

Moving on, the next part will be implementing the method to use the check-boxes.

 protected void gvCheckboxes_RowCreated(object sender, GridViewRowEventArgs e)  
     {  
       if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))  
       {  
         CheckBox selectbookchklist = (CheckBox)e.Row.Cells[1].FindControl("selectbookchklist");  
         CheckBox selectallbookchklist = (CheckBox)this.grdData.HeaderRow.FindControl("selectallbookchklist");  
         selectbookchklist.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');", selectallbookchklist.ClientID);  
       }  
     }  

In here, I created a class file named CBookManager.cs within an App_Code folder. Remember to set it's build action to compile.

Also, if you are retrieving data records that are not deleted, remember to insert this in your SQL code:
RecordDeleteDate IS NULL


 public int deleteOneBook(String inBookRecordId)  
     {  
       int numOfRecordsAffected = 0;  
       SqlCommand cmd = new SqlCommand();  
       SqlConnection conn = new SqlConnection();  
       string sqlText = "UPDATE Book SET RecordDeleteDate=GETDATE()";  
       sqlText += " WHERE BookRecordId=@inBookRecordId";  
       string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       conn.ConnectionString = connString;  
       cmd.Connection = conn;  
       //Prepare a valid DELETE SQL statement  
       cmd.CommandText = sqlText;//setup the SQL in the cmd object  
       cmd.Parameters.Add("@inBookRecordId", SqlDbType.Int);  
       cmd.Parameters["@inBookRecordId"].Value = inBookRecordId;  
       conn.Open();  
       numOfRecordsAffected = cmd.ExecuteNonQuery();  
       conn.Close();  
       return numOfRecordsAffected;  
     }  

Additional part

If you have a function that uses the recordId in the gridview such as an update function. You may choose to consider this part :D

 int intRowIndexWhichUserHasClicked = 0;  
       // If multiple buttons are used in a GridView control, use the  
       // CommandName property to determine which button was clicked.  
       if (e.CommandName == "UpdateOneBookCommand")  
       {  
         intRowIndexWhichUserHasClicked = Convert.ToInt32(e.CommandArgument);  
         Response.Redirect("ADMupdateBook.aspx?BookRecordId=" + grdData.DataKeys[intRowIndexWhichUserHasClicked].Value);  
       }  




No comments: