Showing posts with label button. Show all posts
Showing posts with label button. Show all posts

Thursday, December 19, 2013

Check for duplicate record

How to check for duplicate records so that your database will not be filled with same content over and over again??


In this tutorial, I am checking for duplicate record for a book so that when adding a book record, duplicated book record will NOT be added.

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, in the .aspx file, add this code below to allow user to add a book name record.

 <b><asp:Label ID="lblbookname" Text="Enter book name: " runat="server"></asp:Label></b><br />  
   <asp:TextBox ID="bookname" runat="server" Width="300px"></asp:TextBox><br />  
   <div id="bookdivMessage" runat="server"></div><br />  
   
 <b><asp:Button ID="addbookbtn2" Text="Add Book" runat="server" Width="100px"   
       onclick="addbookbtn_Click"></asp:Button></b><br />   

Next, in the aspx.cs file (code behind file), add this part to allow access and usage of Sql and Class file which will be created later.

 using System.Data;  
 using System.Data.SqlClient;  
 using ProjectName.App_Code;  


 protected void addbookbtn_Click(object sender, EventArgs e)   
    {   
     int numOfRecordsAffected = 0;   
     CBookManager BooksManager = new CBookManager();   
     string collectedBookName = "";   
     collectedBookName = bookname.Text;   
    Boolean isThereDuplicateRecordByBookName = false;   
     isThereDuplicateRecordByBookName = BooksManager.checkDuplicateRecordByBookName(collectedBookName);   
     if (isThereDuplicateRecordByBookName == true)   
     {   
      bookdivMessage.InnerHtml = "There is already a book with this name";   
     }   
     if (isThereDuplicateRecordByBookName == false)   
     {   
      numOfRecordsAffected = BooksManager.addOneBook(collectedBookName);   
     divMessage.InnerHtml = "<u>" + numOfRecordsAffected + "</u> record has been added";  
     }   
     else   
     {   
      numOfRecordsAffected = 0;   
     divMessage.InnerHtml = "<u>" + numOfRecordsAffected + "</u> record has been added";  
     }   
    }   


After completing the code behind file, create a file named App_Code within your project and create a class file named CBookManager. After creating CBookManager, change the build action to COMPILE and add the following codes below.

 using System.Data;  
 using System.Data.SqlClient;  
 using System.Configuration;  -- To use Connection String

This code below is to check for duplicate record within the database. If there is duplicate record within database, record will not be added. However, if duplicate record == false, record will be added successfully.

 public Boolean checkDuplicateRecordByBookName(String inBookName)  
     {  
       int result = 0;  
       SqlCommand cmd = new SqlCommand();  
       SqlConnection conn = new SqlConnection();  
       string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       conn.ConnectionString = connString;  
       cmd.Connection = conn;  
   
       string SqlText = "SELECT COUNT(*) FROM BOOK WHERE BOOKNAME = @inBookName";  
       cmd.CommandText = SqlText;  
       cmd.Parameters.Add("@inBookName", SqlDbType.VarChar, 100);  
       cmd.Parameters["@inBookName"].Value = inBookName;  
       conn.Open();  
       result = Convert.ToInt32(cmd.ExecuteScalar());  
       conn.Close();  
       if (result >= 1)  
       {  
         return true;  
       }  
       else  
       {  
         return false;  
       }  

Next, to activate the add book function, insert the following code:

 public int addOneBook(String inBookName)  
     {  
       int numOfRecordsAffected = 0;  
       SqlCommand cmd = new SqlCommand();  
       SqlConnection conn = new SqlConnection();  
       //Setup of the connection information   
   
       string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       conn.ConnectionString = connString;  
   
       cmd.Connection = conn;//Tell the Command object use the Connection object  
   
       //Prepare a INSERT SQL template  
       string sqlText = "INSERT INTO Book (BookName) ";  
       sqlText += " VALUES (@inBookName)";  
       //setup the SQL in the cmd object  
   
       cmd.CommandText = sqlText;  
   
       cmd.Parameters.Add("@inBookName", SqlDbType.VarChar, 100);  
       cmd.Parameters["@inBookName"].Value = inBookName;  
         
       conn.Open();  
       numOfRecordsAffected = cmd.ExecuteNonQuery();  
       conn.Close();  
   
       return numOfRecordsAffected;  
     }  

Remember to create a Book database, which consists of BookName, type = varchar, 100 characters.

We have come to the end of this tutorial :D Thanks for your patience and have fun coding :)

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);  
       }  




Thursday, December 05, 2013

Simple search function asp.net C#

How to implement a basic search button in your website? 

Note: in this tutorial, this is a book search function with regards to a gridview

In your webform, insert these few lines where you want the search function to be.

 <asp:TextBox ID="txtSearch" runat="server" Width="200px" ></asp:TextBox>  
   <asp:Button ID="btnSearch" runat="server" Text="Search" Width="70px"   
       onclick="btnSearch_Click"/>  

Next, in your code behind file, implement this method

 using System.Data;  
 using System.Data.SqlClient;  
 using ProjectName.App_Code;  

protected void btnSearch_Click(object sender, EventArgs e)  
     {  
       DataTable dtBookData = new DataTable();  
       CBookManager BooksManager = new CBookManager();  
       string searchName = "";  
       searchName = txtSearch.Text;  
       dtBookData = BooksManager.searchBookByName(searchName);  
       grdData.DataSource = dtBookData;  
       grdData.DataBind();  
     }  

Next, in your class file, App_Code - CBookManager, insert this part.

 public DataTable searchBookByName(String inSearch)  
     {  
       SqlDataAdapter ad = new SqlDataAdapter();  
       SqlCommand cmd = new SqlCommand();  
       SqlConnection connection = new SqlConnection();  
       DataSet ds = new DataSet();  
       String sqlText = "SELECT Book.BookRecordId, Book.BookName FROM Book";  
       sqlText += " WHERE BookName LIKE @inBookName";  
       string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;  
       connection.ConnectionString = connString;  
       cmd.Connection = connection;  
       cmd.CommandText = sqlText;  
       cmd.Parameters.Add("@inBookName", SqlDbType.VarChar, 100);  
       cmd.Parameters["@inBookName"].Value = "%" + inSearch + "%";  
       ad.SelectCommand = cmd;  
       connection.Open();  
       ad.Fill(ds, "BookData");  
       connection.Close();  
       return ds.Tables["BookData"];//Return the data table to the web form  
     }  

After some editing, you should be able to search for the correct data. Good luck in implementing this search function. :)