Archive for category Asp.Net

How to hide columns based on values selected in checkbox

Introduction:

How to hide columns based on values selected in checkbox

Description:

In this article I am going to explain how to hide columns in grid view based on user selection in checkbox. We can achieve this requirement with both client side and server side approach. Here I am going to explain the client side approach where we uses Jquery to hide column in gridview.

Gridview will render as table with header and rows at runtime, we will use jquery selector to access this header and calculate selected column index and then hide or show accordingly.

Function to hide and display Column

 <script type="text/javascript">
        $(document).ready(function () {
            //Attach click to checkboxlist
            $("#CheckBoxList1").click(function () {
                //loop through each item in checkboxlist
                $("[id*=CheckBoxList1] input").each(function () {
                    //Get the Gridview header row
                    var tblhead = $("#GridView1 th");
                    //Get the selected column index in gridview
                    var columnIndex = tblhead.index($("table[id*=GridView1] th:contains('" + $(this).next().html() + "')")) + 1;
                    //check if current items in checkboxlist is selected or not
                    if ($(this).is(":checked")) {
                        //if so then hide that column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").hide();
                    } else {
                        //if not then display the column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").show();
                    }
                });
            });
        });
    </script>

Complete Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    	<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    	<link rel="stylesheet" href="/resources/demos/style.css">
    <script type="text/javascript">
        $(document).ready(function () {
            //Attach click to checkboxlist
            $("#CheckBoxList1").click(function () {
                //loop through each item in checkboxlist
                $("[id*=CheckBoxList1] input").each(function () {
                    //Get the Gridview header row
                    var tblhead = $("#GridView1 th");
                    //Get the selected column index in gridview
                    var columnIndex = tblhead.index($("table[id*=GridView1] th:contains('" + $(this).next().html() + "')")) + 1;
                    //check if current items in checkboxlist is selected or not
                    if ($(this).is(":checked")) {
                        //if so then hide that column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").hide();
                    } else {
                        //if not then display the column
                        $("table[id*=GridView1]").find("th:nth-child(" + columnIndex + "), td:nth-child(" + columnIndex + ")").show();
                    }
                });
            });
        });
    </script>
</head>
<body>
<form id="form1" runat="server">
        <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Value="AddressID">AddressID</asp:ListItem>
            <asp:ListItem Value="AddressLine1">AddressLine1</asp:ListItem>
            <asp:ListItem Value="City">City</asp:ListItem>
            <asp:ListItem Value="StateProvinceID">StateProvinceID</asp:ListItem>
            <asp:ListItem Value="PostalCode">PostalCode</asp:ListItem>
            <asp:ListItem Value="ModifiedDate">ModifiedDate</asp:ListItem>
        </asp:CheckBoxList>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True" DataSourceID="SqlDataSource2">
            <Columns>
                <asp:BoundField DataField="AddressID" HeaderText="AddressID" />
                <asp:BoundField DataField="AddressLine1" HeaderText="AddressLine1" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="StateProvinceID" HeaderText="StateProvinceID" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
                <asp:BoundField DataField="ModifiedDate" HeaderText="ModifiedDate" />
            </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT top 20 [AddressID], [AddressLine1],City,StateProvinceID,PostalCode,ModifiedDate FROM Person.Address"></asp:SqlDataSource>
    </form>

</body>
</html>

demo

Advertisements

, , , , , ,

Leave a comment

How to load data from database to Asp.Net Gridview using WebAPI

Introduction:

In this article we are discussing how to load data from database to Asp.Net Gridview using WebAPI.

Description:

We use WebAPI to get the data from database and then use the Jquery getJSON() method to Load JSON-encoded data from the server using a GET HTTP request.

Implementation:

In the New ASP.NET Project dialog, select the Empty template. Under “Add folders and core references for”, check WebForms , Web API. Click OK.

2016-04-30 19_11_49-Microsoft Visual Studio (Administrator)

When using WEBAPI you will get data in client side and you need to manipulate it at client side so that the data will get populated in Gridivew. Point to note here is we cannot go with the normal approach of setting DataSource and calling DataBind method. We have various options to load data into grid like AngularJs, Jquery etc.

As mentioned earlier in this article I am using getJSON() method to fetch the value and then populate the data in gridview. Gridview will load as table at runtime we will access this table and then append the values to it.

2016-04-30 14_29_24-http___localhost_52678_WebForm1.aspx - Internet Explorer

Sample Code:

HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script type="text/javascript">
        //Code to load the data to gridview on pageload
        $(document).ready(function () {
           //Here you need to provide the webapi address
            $.getJSON('api/Customer')
                .done(function (data) {
                    $.each(data, function (key, item) {
                        //Add the result to gridview
                        $("#GridView1").append("

<tr>

<td>" + item.CustomerID + "</td>


<td>" + item.CompanyName + "</td>


<td>" + item.ContactName + "</td>


<td>" + item.ContactTitle + "</td>


<td>" + item.Address + "</td>

</tr>
");
                    });
                })
            .fail(function (d) {
                alert("error occured" + d.responseText);
            });
        });
    </script>
</head>
<body>
<form id="form1" runat="server">
<div>
            <asp:GridView ID="GridView1" runat="server" Width="1000px" ShowHeaderWhenEmpty="true"                 CellPadding="0" CellSpacing="0">
            </asp:GridView></div>
</form>

</body>
</html>

C#:

First we need to populate an empty row in GridView. Reason behind this is if we didn’t assign any datasource then the GridView won’t populate at runtime and we won’t be able to access it at client side.

protected void Page_Load(object sender, EventArgs e)
        {
            //Load and empty row to gridview
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(&quot;CustomerID&quot;);
                dt.Columns.Add(&quot;CompanyName&quot;);
                dt.Columns.Add(&quot;ContactName&quot;);
                dt.Columns.Add(&quot;ContactTitle&quot;);
                dt.Columns.Add(&quot;Address&quot;);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

WebAPI Code:

When we add the WebAPI references in your project you will see a Model folder and Controller folder.

2016-04-30 19_20_50-WebAPISample - Microsoft Visual Studio (Administrator)

Model

Here we add the Model classes which basically represents data in WebAPI. For this article we add Customer class. Right Click on the Model folder and choose Add and then select class file. Name it like Customer

public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
    }

Controllers:

In controller we will add the code to fetch values from database. Right click on the Controllers folder and Choose Add and then select Controller. In code you can see an HttpGet entry added above to GetCustomers method. This is because Rest WebAPI is making use of verbs(Get,Post,Put,Delete) for each actions in Read,Create,Update,Delete respectively. You can get more details from here

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiSample.Models;

namespace WebApiSample.Controllers
{
    public class CustomerController : ApiController
    {
        [HttpGet]
        public IEnumerable<Customer> GetCustomers()
        {
            Customer[] aryCustomers = null;
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWINDConnectionString"].ToString()))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "SELECT TOP 10 CustomerID,CompanyName,ContactName,ContactTitle,Address FROM Customers";
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        List<Customer> lstcustomers = new List<Customer>();
                        while (reader.Read())
                        {
                            lstcustomers.Add(new Customer
                            {
                                CustomerID = reader["CustomerID"].ToString(),
                                CompanyName = reader["CompanyName"].ToString(),
                                ContactName = reader["ContactName"].ToString(),
                                ContactTitle = reader["ContactTitle"].ToString(),
                                Address = reader["Address"].ToString()
                            });
                            aryCustomers = lstcustomers.ToArray();
                        }
                    }
                }
            }
            return aryCustomers;
        }
    }
}

, , , , , , ,

Leave a comment

Search and Populate GridView from database using Jquery Ajax

Introduction:

In this article I am going to explain how to search and Populate GridView from database using Jquery Ajax.

Prerequisites:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

I have used Address table from AdventureWorks Database. You can download it from here.

Implementation:

Here we are make use of Jquery Ajax post method in Jquery to check if record exists in database and get the details on the blur event of textbox.

HTML

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     <title runat="server"></title>
     <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
     <script type='text/javascript'>
         $(document).ready(function () {
             //Attach on change event to textbox here
             $("#TextBox1").change(function () {
                 //Remove all previously added rows in gridview
                 $("[id*=sampleGV] tr").not($("[id*=sampleGV] tr:first-child")).remove();
                 $.ajax({
                     type: "POST",
                     //Call the method to get data from database 
                     url: "WebForm4.aspx/GetOrderDetails",
                     //Pass the value from textbox to method
                     data: '{"addressID":' + $("#TextBox1").val() + '}',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function (result) {
                         //Add the resul to gridview
                         $("#sampleGV").append("<tr><td>" + result.d[0][0] + "</td><td>" + result.d[0][1] + "</td><td>" + result.d[0][2] + "</td></tr>");
                     },
                     failure: function (response) {
                         alert(response.d);
                     },
                     error: function (response) {
                         alert(response.d);
                     }
                 });
 
             });
         });
     </script>
 </head>
 <body class="myCss">
     <div>
         <form id="form1" runat="server" class="hidden">
             <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
             <asp:GridView ID="sampleGV" runat="server" Width="1000px" ShowHeaderWhenEmpty="true"
                 CellPadding="0" CellSpacing="0">
             </asp:GridView>
         </form>
     </div>
 </body>
 </html>
 

C#:

First we need to populate an empty row in GridView. Reason behind this is if we didn’t assign any datasource then the GridView won’t populate at runtime and we won’t be able to access it at client side

 protected void Page_Load(object sender, System.EventArgs e)
 {
         //Load and empty row to gridview
         if (!IsPostBack) {
                DataTable dt = new DataTable();
                dt.Columns.Add("AddressID");
                dt.Columns.Add("AddressLine1");
                dt.Columns.Add("City");
                sampleGV.DataSource = dt;
                sampleGV.DataBind();
         }
 }
 

Next is the GetOrderDetails method which will read the parameter from client side and the search the database and then pass the result set back. Note the [Services.WebMethod()] attribute I added to the GetOrderDetails method,this is important  otherwise the serverside method will not be called from client side jQuery AJAX call.

[Services.WebMethod()]
public static Array GetOrderDetails(string addressID)
{
	//Create sql connection object here
	SqlConnection conn = null;
	//Create sql DataTable object here
	DataTable dt = new DataTable();
	//Create sql SqlDataAdapter object here
	SqlDataAdapter da = default(SqlDataAdapter);
	//Create sql ArrayList object here
	ArrayList rows = new ArrayList();
	//Get the connectionstring from webconfig file
	string connection = ConfigurationManager.ConnectionStrings("Adventure WorksConnectionStringPersonal").ConnectionString;
	//Create sql SqlConnection object here and assign the conenctionstring
	conn = new SqlConnection(connection);
	//Create sql query here
	string sql = "SELECT AddressID,AddressLine1,City FROM Person.Address a WHERE a.AddressID = @AddressID";
	//Create sql SqlCommand and assign connection and command here
	SqlCommand cmd = new SqlCommand(sql, conn);
	//Pass your parameter here
	cmd.Parameters.AddWithValue("@AddressID", addressID);
	//Open the SQLConnection here
	conn.Open();
	//Create SqlDataAdapter object here
	da = new SqlDataAdapter(cmd);
	using (DataSet ds = new DataSet()) {
		//Load the DataTable
		da.Fill(dt);
		foreach (DataRow dataRow in dt.Rows) {
			rows.Add(dataRow.ItemArray.Select(item => item.ToString()));
		}
		//Create an array and then return the values
		return rows.ToArray();
	}
	conn.Close();
}

Demo

, , , ,

Leave a comment

How to highlight the selected rows in Repeater using Jquery

Introduction:

In this article I am going to explain how to highlight the selected row in Repeater control using Jquery.  At runtime Repeater control will render as table we will be manipulating this table structure to access each row and then use the css to highlight the row.

Prerequisites:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

Solution:

We will use the below css to hightlight the rows in gridview.

<style type="text/css">
        .highlightRow
        {
            background-color: #9999FF;
        }
    </style>

Jquery Code:             

Below Jquery function will remove the css from all other rows except the selected row

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
 <script>
    $(function () {
         $(".trclass").click(function () {
            $(this).addClass("highlightRow").siblings().removeClass("highlightRow");
          });
     });
 </script>

HTML

   <asp:Repeater runat="server" ID="Repeater1">
            <HeaderTemplate>
                <table width="500px" border="1px">
                    <tr style="background-color: #fb7700">
                        <td>Value1
                        </td>
                        <td>Value2
                        </td>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr class="trclass">
                    <td>
                        <asp:Label ID="lblValue1" runat="server" Text='<%# Eval("val1") %>'></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="lblValue2" runat="server" Text='<%# Eval("val2") %>'></asp:Label>
                    </td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Below code is to populate dummy data, you dont need this code if you are populating the repeater from database in code behind.

C#:

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable table1 = new DataTable();
                table1.Columns.Add("val1");
                table1.Columns.Add("val2");
                table1.Rows.Add("Value1", "Message1");
                table1.Rows.Add("Value2", "Message2");
                table1.Rows.Add("Value3", "Message3");
                table1.Rows.Add("Value4", "Message4");
                table1.Rows.Add("Value5", "Message5");
                table1.Rows.Add("Value6", "Message6");
                table1.Rows.Add("Value7", "Message7");
                Repeater1.DataSource = table1;
                Repeater1.DataBind();
            }
        }

Demo

, , , , ,

Leave a comment

How to implement a GridView in MVC

Introduction:

In this article I am going to explain how to implement a GridView in MVC.

Prerequisites:

We are going to use Grid.Mvc Jquery plugin to implement GridView in MVC. You can get more details of this control from here.

To use Grid.Mvc we have to first add the necessary Jquery files to solution. One easy option to do this is to use the Nugget package to add Grid.Mvc to your solution. You can use the below command

install-package Grid.Mvc

After successful installation you will be able to see the below messages.

You can also download the file and add it to your solution manually.

Implementation:

Here I am going to explain how to implement GridView in MVC without using the table approach.

Model:

First you need to create a class in the Model. In this example I have used the DatabaseFirst approach.

You can use the below steps to generate the class files

  • Right click on the Model folder
  • Select Add option
  • And then select the New Item option
  • Select the Net Entity Data Model option and Provide a name for it
  • In the Entity Data Model Wizard, Select EF Designer from database and click on Next

If you already have connection string configured then you can select that from the available list.

If you don’t have the connection string configured then use the New Connection option and create the connection

  • Expand the Tableoption and then select the tables which you want
  • Click on Finish
  • You will have necessary class files generated in your solution now

You can get more details about how to use DatabaseFirst approach from this link.

Controller:

Now we have the Model files created from database. Next step is to fetch the data from database and then pass it to the View from Controller. We will have a basic select in EF for this demo. You can modify it as per your need.

  public ViewResult Index()
        {
            //Create db context object here this is test record
            AdventureWorksDbContext dbContext = new AdventureWorksDbContext();
            //Get the value from database and then Pass it View
            var items = dbContext.Addresses.Take(10);
            return View(items.ToList());
        }

View:

In View you can use the below code to create GridView in MVC. This will generate a very basic GridView in MVC View

@model IEnumerable<MvcApplication1.Models.Address>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <!-- CSS Includes -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link href="@Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" type="text/css" />
    <!-- Script Includes-->
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="@Url.Content("~/Scripts/gridmvc.min.js")" type="text/javascript"> </script>
</head>
<body>
    <div style="width:550px">
        @*Refer the GridView reference here*@
        @using GridMvc.Html
        @Html.Grid(Model).Columns(columns =>
           {
               //Put the column details here
               columns.Add(s => s.AddressID).SetWidth(110).Sortable(true);
               columns.Add(s => s.AddressLine1).Sortable(true).SetWidth(110);
               columns.Add(s => s.City).Sortable(true).SetWidth(110);
               columns.Add(s => s.ModifiedDate).Sortable(true).SetWidth(110);
           }).WithPaging(20)
    </div>
</body>
</html>

Demo

Here I have used very little options, Grid.Mvc plugin supports variety of options like CustomColumns, Button controls in column, Editing in Gridview. You can get more details of this control from here.

, , ,

Leave a comment

How to make a CheckBoxList items single select in Asp.Net

Introduction:

In this article I am going to explain how to make a CheckBoxList single select in asp.net

Description:

Usually RadioButtonList is the control which allow the user to select a single selection of items inside it and users will use CheckBoxList control to allow multiple selection of items. However in some cases we need to make the CheckBoxList control a single select one. You can make use of Javascript to achieve this.

The logic here is to attach a Javascript function in onclick event of each items in CheckboxList.

Javascript Function

<script type = "text/javascript">
            function UncheckOthers(objchkbox) {
                //Get the parent control of checkbox which is the checkbox list
                var objchkList = objchkbox.parentNode.parentNode.parentNode;
                //Get the checkbox controls in checkboxlist
                var chkboxControls = objchkList.getElementsByTagName("input");
                //Loop through each check box controls
                for (var i = 0; i < chkboxControls.length; i++) {
                    //Check the current checkbox is not the one user selected
                    if (chkboxControls[i] != objchkbox && objchkbox.checked) {
                        //Uncheck all other checkboxes
                        chkboxControls[i].checked = false;
                    }
                }
            }
</script>

HTML:

 <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Text="FirstValue" Value="1" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Second Value" Value="2" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Third Value" Value="3" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Fourth Value" Value="4" onclick="UncheckOthers(this);">
            </asp:ListItem>
            <asp:ListItem Text="Fifth Value" Value="5" onclick="UncheckOthers(this);">
            </asp:ListItem>
</asp:CheckBoxList>

Demo

, , ,

4 Comments

How to Crop the Image using CropImage.Net tool in Asp.Net

Introduction:

In this article I am going to explain how to crop an Image using CropImage.Net

Prerequisites:

You can download the dll files needed to use CropImage.Net from this link. Once you have a downloaded the files you need to add the dll files to your solution. You can follow the below steps to add the dlls.

  • Open your Project within the Solution Explorer
  • Right-click the References folder and Choose Add Reference options
  • Find and select the dlls which needs to be added to your solution
    • ImageResizer.dll
    • Imazen.Crop.dll
    • System.Web.Extensions.dll (You may need to use the browse button if you are not finding the dll in available list)
  • Click the Ok button to add it to your Project.

Now you have all the files added to your project

Details of CropImage.Net Control:

CropImage.Net exposes method called Crop, which actually Crops the original image and saves it to the specified path. This method have two overrides one with destinationpath as parameter and another one with destinationpath and appendCorrectExtension.

public void Crop(string destPath);
public void Crop(string destPath, bool appendCorrectExtension)

 Implementation:

Here I am going to explain the steps on how to use CropImage.Net tool to crop the images using Asp.Net.

In this demo I will upload a file and then the uploaded file will be shown in an image control. Then with the help of CropImage control the image will be cropped and shown in another image control called result.

First Step is to register the ImageCrop control in your page like given below

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

Then you need add the below CropImage control to your page and then set it Image property to the Image control from which Image is used to crop.

<ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />

Then we use the Crop method to crop and save the image to the destination path provided.

//Save the copy in local folder
CropImage1.Crop(MapPath("~/images"), true);

You also need to add the below configurations to your webconfig file

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" />
    <httpModules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </httpModules>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>
    </modules>
  </system.webServer>
</configuration>

Complete Code:

HTML:

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Croping Image using ImageResizer in .Net</h3>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <asp:Image ID="Image1" runat="server" ImageUrl="" />
            

            <ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />
            

            <asp:Button ID="Button1" runat="server" Text="Crop" OnClick="btnCrop_Click" />
            <h3>The result</h3>
            <asp:Image ID="Result" runat="server" Visible="false" />
        </div>
    </form>
</body>
</html>

C#:

protected void btnCrop_Click(object sender, EventArgs e)
    {

        //Show the Result Image control 
        Result.Visible = true;
        //Assign the image url from CropImage control
        Result.ImageUrl = CropImage1.CroppedUrl;

        //Save the copy in local folder
        CropImage1.Crop(MapPath("~/images"), true);

        //You can also get the coordinates from CropImage if you want to show to the user
        this.Title = CropImage1.X + "," + CropImage1.Y + "," + CropImage1.X2 + "," + CropImage1.Y2;

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Check if file upload is having any value
        if (FileUpload1.HasFile)
        {
            try
            {
                //Get the uploaded filename from FileUpload Control
                string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                //Save the file to folder
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                //Show the uploaded image in Image Control which is tagged to the Image Cropping Control
                Image1.ImageUrl = "~/images/" + filename;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.ToString());
            }
        }
    }

Note that I have used the folder which is inside in my solution.You can see that in the image given above. If you have a different you need to change the path accordingly.

Demo

, , , , ,

3 Comments