ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal :: How to Delete Record in GridView Using ASP.Net Ajax and jQuery

clock January 13, 2015 06:14 by author Mark

How to Delete Record in GridView Using ASP.Net Ajax and jQuery

This article will explains how to delete record in GridView using ASP.NET Ajax and jQuery

  • Now first create the Employee table in the database.

CREATE TABLE tbl_Emp(Empid int NULL,EmpName varchar(250) NULL, Gender varchar(20), EmpAddress varchar(500) NULL,City varchar(250) NULL,Salary int NULL, Fk_DepId int)

  • And insert some records into the table:

INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(1, 'A' , 'Male', 'Demo Address', 'Agra', 4000, 3)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(2, 'B' , 'Male', 'Demo Address', 'Ghaziabad', 0, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(3, 'C' , 'Male', 'Demo Address', 'Agra', 1000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(4, 'D' , 'Female', 'Demo Address', 'Mathura', 1000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(5, 'E' , 'Female', 'Demo Address', 'Agra', 4000, 3)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(6, 'F' , 'Male', 'Demo Address', 'Agra', 5000, 2)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(7, 'G' , 'Male', 'Demo Address', 'Noida', 4000, 1)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(8, 'H' , 'Male', 'Demo Address', 'Agra', 4000, 5)  
INSERT INTO tbl_Emp(Empid, EmpName, Gender, EmpAddress, City, Salary, Fk_DepId)VALUES(9, 'I' , 'Male', 'Demo Address', 'Noida', 5000, 1) 

  • After creating the table create the application. New -> Web Site.
  • Provide the name “DeleteRecordfromGridViewUsingJQueryAjax”.
  • Then create a new item.

Your aspx page looks likes this:

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
        <title></title> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
            <div> 
                <asp:GridView ID="gvEmp" AutoGenerateColumns="false"CellPadding="4" runat="server"> 
                    <Columns> 
                    <asp:BoundField HeaderText="EmpId" DataField="EmpId"/>
                    <asp:BoundField HeaderText="EmpName"DataField="EmpName" />

                    <asp:BoundField HeaderText="Gender" DataField="Gender" /> 
            <asp:BoundField HeaderText="EmpAddress" DataField="EmpAddress" /> 
            <asp:TemplateField> 
            <ItemTemplate> 
            <asp:HiddenField ID="hdnEmpId" runat="server" Value='<%#Eval("EmpId") %>'></asp:HiddenField>                                  <asp:LinkButton ID="btnDelete" Text="Delete Emp" runat="server"OnClientClick="DeleteConfirmbox(this.id);"></asp:LinkButton>
                         </ItemTemplate> 
                        </asp:TemplateField> 
                    </Columns> 
          <HeaderStyle BackColor="#5d5d5d" FontBold="true"ForeColor="White" />
                </asp:GridView> 
            </div> 
        </form>
         <script src="Scripts/jquery-1.7.1.min.js"></script>        
        <script type="text/javascript"> 
            function DeleteConfirmbox(val) { 
                // confirm meg check for delete 
                var result = confirm('Are you sure delete Emp Record?'); 
                if (result) {        
                  // this is for get hdnvalue id 
                  var value = val.replace("btnDelete", "hdnEmpId"); 
                  $.ajax({ 
                  type: "POST", 
                  contentType: "application/json; charset=utf-8", 
                  url: "Default.aspx/DeletegvEmpData",//this for calling the web method function in cscode. 
                  data: '{empid: "' + $("#" + value).val() + '" }',// empid value                     
                  dataType: "json", 
                  success: OnSuccess, 
                  failure: function (data) { 
                  alert(data); 
                        }          
                    });                        
                    return false; 
                } 
            }        
            // function OnSuccess 
            function OnSuccess(response) { 
                return false; 
            if (response.d == 'true') 
            {              
            }      
        } 
    </script> 
</body> 
</html> 

  • Now add “using System.Data.SqlClient;” and “using System.Data;” in the code behind and write the following code to delete the record in the grid view in the database.

protected void Page_Load(object sender, EventArgs e)  
  {  
      if (!IsPostBack)  
      {  
          Bindgv();  
      }  
  }       
  protected void Bindgv()  
  {  
      SqlConnection con = new SqlConnection("data source=LENOVO;initial catalog=practise;UID=sa;PWD=connect;");       
      con.Open();  
      SqlCommand cmd = new SqlCommand("Select Top 10 EmpId, EmpName, Gender, EmpAddress from tbl_Emp", con);  
      SqlDataAdapter da = new SqlDataAdapter(cmd);  
      DataSet ds = new DataSet();  
      da.Fill(ds);  
      con.Close();  
      gvEmp.DataSource = ds;  
      gvEmp.DataBind();       
  }       
  [System.Web.Services.WebMethod]  
  public static string DeletegvEmpData(int empid)  
  {  
      string strmsg = string.Empty;  
      SqlConnection con = new SqlConnection("data source=LENOVO;initial catalog=practise;UID=sa;PWD=connect;");       
      SqlCommand cmd = new SqlCommand("delete from tbl_Emp where EmpId= @Empid", con);       
      con.Open();  
      cmd.Parameters.AddWithValue("@Empid", empid);  
      int retval = cmd.ExecuteNonQuery();  
      con.Close();       
      if (retval == 1)  
          strmsg = "true";  
      else  
          strmsg = "false";                   
      return strmsg;  
  }
Add the jQuery library reference in aspx page:
    <script src="Scripts/jquery-1.7.1.min.js"></script> 

Finished, Now you can run this page.

TOP Recommended ASP.NET Hosting

ASPHostPortal.com is the leading provider of Windows hosting and affordable ASP.NET, ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. Only $1.00 Month You can develop your bussines. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability. 

 

 



ASP.NET Hosting - ASPHostPortal.com :: Scaffolding for ASP.NET Webforms

clock January 7, 2015 05:41 by author Ben

Those who knows ASP.NET MVC, might already knows the power of scaffolding. With VS.Net 2013 we will have scaffold template included for asp.net web forms.  By scaffold template you can generate a boilerplate code for asp.net web forms in a min. The Web Forms scaffold generator can automatically build Create-Read-Update-Delete (CRUD) views based on a model.

 


Step by Step example of using scaffold template inside asp.net web forms to generate CRUD operations.

Step 1:
Download VS.Net 2013 Express Preview

Step 2:
Create Asp.net WebForm Project

Step 3:
Add Model Class and named it as "Product.cs"  (Right click Model class and Add new class)


Step 4:
Create POCO Class with following content in it.  Yes you can take advantage of DataAnnotations of Entity framework.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebApplication3.Models
{
    public class Product
    {
        [ScaffoldColumn(false)]
        public int ID { get; set; }

        [StringLength(25)]  
        public string ProductName { get; set; }
        public string Description { get; set; }
       
        [DataType(DataType.Currency)]
        public int Price { get; set; }       
    }
}


In above code

  • [ScaffoldColumn(false)] will not generate any presentation code for that field
  • [StringLenght(25)] will limit product name upto 25 characters only.
  • [DataType(DataType.Currency)] will limit to enter only proper currency value.

Step 5:
Build your application.  (Cntrl + Shift + B)

Step 6:
Now its time to use scaffold template to generate code for CRUD operations in asp.net web forms.
Right click on model class and add scaffold for Product class.


Step 7:
Click on Add button as shown in figure to "Generates ASP.NET Web Forms pages for read/write operations based on a given data model."


Step 8:
Select Model class as "Product.cs", Since we haven't created or have any data context class, select "Add new data context" and Click on "Add" button.


Step 9:
If you wish you can change name of your data context class.  For this demo purpose I am keeping everything to default generated by VS.Net.  Press "OK" button.


Step 10:
You will noticed that VS.Net 2013 has generated new data context file inside model folder and has also created CRUD operations for Product class.


Step 11:
Run the application and enjoy the boilerplate code...  You will also noticed that web forms project has extension-less url and also has responsive design using Twitter bootstrap out of the box...

Type the url: /Product  notice it is extension-less url and


Click on "Create new" link and create new product

Data Entry few product.  Notice fancy validation on entering wrong values.  "Everything is out of box, you don't need to write a single line of code to make this working... Isn't that cool"


Product Listing


Similarly you can edit record, delete record. Hope you enjoyed this post...

 



ASP.NET Hosting - ASPHostPortal :: How To Compare Two Images In ASP.NET

clock January 6, 2015 06:05 by author Mark

Compare Two Images In ASP.NET

This article I will explains how to compare two images in ASP.NET. You also can compare images from a database. Databases do not support binary data comparison.
For comparing two images I'm taking both images from outside but you can replace that with database also. It requires extensive conversion like byte array to image and image to bitmap. In this article I'm comparing each pixel of a bitmap.
Image comparison is not possible in any database because the binary data may not be the same. You can try it with data length also but it will not give exact result.

Using Code:

First we convert our uploaded images into a byte array for converting this byte array into images again and then this byte array are again converted into bitmap for comparison.
    byte[] _barray1;
    byte[] _barray2;

Next we have to read the bytes of uploaded images into our byte arrays like bellow. Here you can alternatively use a database field, which means here we can read the database binary data into our byte array. Here instead of reading bytes from Upload control you can read it from database.

//Reading Bytes From Uploaded Images
            if (FileUpload1.HasFile && FileUpload2.HasFile)
            {
               using(BinaryReader reader1=new BinaryReader(FileUpload1.PostedFile.InputStream))
               {
                   using (BinaryReader reader2=new BinaryReader(FileUpload2.PostedFile.InputStream))
                   {
                       _barray1 = reader1.ReadBytes(FileUpload1.PostedFile.ContentLength);
                       _barray2 = reader2.ReadBytes(FileUpload2.PostedFile.ContentLength);
                   }
               }
            }

Passing this two byte array to our compare method is not possible; for that we have to convert this byte array to images and then the images to Bitmap and pass the two bitmap to our compare method and show the results.

//Converting Byte Array To Image And Then Into Bitmap
            ImageConverter ic = new ImageConverter();
            Image img = (Image)ic.ConvertFrom(_barray1);
            Bitmap bmp1 = new Bitmap(img);
            Image img1 = (Image)ic.ConvertFrom(_barray2);
            Bitmap bmp2 = new Bitmap(img1);
            //Calling Compare Function
            if (Class1.Compare(bmp1,bmp2)==Class1.CompareResult.ciCompareOk)
            {
                Label1.Visible = true;
                Label1.Text = "Images Are Same";
            }
            else if (Class1.Compare(bmp1,bmp2)==Class1.CompareResult.ciPixelMismatch)
            {
                Label1.Visible = true;
                Label1.Text = "Pixel not Matching";
            }
            else if (Class1.Compare(bmp1,bmp2)==Class1.CompareResult.ciSizeMismatch)
            {
                Label1.Visible = true;
                Label1.Text = "Size Is Not Same";
            }

The Compare Method:

This method will perform the actual task of image comparison. This method compares each and every pixel using SHA256Managed and stores the result in enum.
public enum CompareResult
    {
        ciCompareOk,
        ciPixelMismatch,
        ciSizeMismatch
    };

    public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
    {
        CompareResult cr = CompareResult.ciCompareOk;

        //Test to see if we have the same size of image
        if (bmp1.Size != bmp2.Size)
        {
            cr = CompareResult.ciSizeMismatch;
        }
        else
        {
            //Convert each image to a byte array
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());

            //Compute a hash for each image
            SHA256Managed shaM = new SHA256Managed();
            byte[] hash1 = shaM.ComputeHash(btImage1);
            byte[] hash2 = shaM.ComputeHash(btImage2);

            //Compare the hash values
            for (int i = 0; i < hash1.Length && i < hash2.Length && cr == CompareResult.ciCompareOk; i++)
            {
                if (hash1[i] != hash2[i])
                    cr = CompareResult.ciPixelMismatch;
            }
            shaM.Clear();
        }
        return cr;
    }

Conclusion:

This compares two images either from uploaded images or database binary data.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in