Archive for category C#

Implementing Multiselect feature on AutoCompleteExtender

AjaxControlToolkit’s AutoComplete extender is designed to be a single selection control. i.e. When user selects a value the dropdown list will be closed and selected text will be assigned to targeted textbox control.

Recently I got a question on the Asp.net Forums where the user wants to make the AutoCompleteExtender a multi select one. Besides the chosen values should be appended to textbox as comma separated values. This question caught my attention as it was a little tricky.

Here are the details of requirements

  • Keep the dropdown list of options on AutoComplete Extender opened
  • Allow multiple selection on AutoComplete Extender
  • Add the string to target textbox control as comma separated strings

We need to come up with a custom implementation to accomplish this requirement.  When I looked at some threads I found the code to keep the list opened. However, I need to customize it to generate comma separated values.

You can find complete implementation details here

Add a behaviorID to AutocompleteExtender control. We will use this id to close the dropdown list after user selecting values

Now we need to add a button to close the dropdown list after selecting values

Add the following javascript function to your page to close the window

Now we need to customize the inbuilt function “_setText” and “_hideCompletionList” function in order to accomplish our requirement

Complete Code

HTML

C#:

Code to populate the list when user type in characters on textbox

Demo

AutoCompleteExtenderDemo

, , , , ,

Leave a comment

How to display larger numbers on Excel export in C#

Introduction:

In this article I am going to explain a solution to the problem with displaying large numbers (more than 15 numbers) in excel while exporting data in C#.

Issue Description:

By default, excel normally display larger numbers like 123456E+17 when the number overcomes Excel’s precision limit for numbers which is 8 digits. When we export the data from Gridivew to excel the same problem exists.

Excel

Drawback of existing Solution:

One solution to resolve this is to make the column type of excel to text instead of numbers. To this we need to add a single quote (‘) to the numbers which we are exporting. This will resolve the issue of displaying the complete number, however this solution has a drawback as it will display single quote along with the number like ‘123456789011.

Solution to the Problem

To show the number without using single quote we can use a Third Party Excel library called EPPlus. EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). This library offers several features and methods to help the user to generate Excel sheet. You can read the complete details from the link I shared above.

Here in this fix we will use the method LoadFromDataTable to load the data from DataTable to Excel. The same case applies when you Export data from gridview and other controls.

Code

private void ExcelExport(DataTable tbl)
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
                //Load the datatable into the sheet, starting from cell A1.
                ws.Cells["A1"].LoadFromDataTable(tbl, true);
                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=file.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
            }
        }

Before using above code add the below references in your page

using OfficeOpenXml;
using OfficeOpenXml.Style;

Sample usage to above method

DataTable dt = new DataTable();
            dt.Columns.Add("PhoneNo");
            dt.Columns.Add("Name");
            DataRow Sample = dt.NewRow();
            Sample["PhoneNo"] = "12345678911121314";
            Sample["Name"] = "SampleName";
            dt.Rows.Add(Sample);
            ExcelExport(dt);

With above code the exported excel file will look like below

Excel2

You can use Nugget to add the EPPlus in your solution.

 

, , , , , , ,

1 Comment

How to check if an array of elements are in Sequential Order in C#

You can use the SequenceEqual method to check if numbers are in Sequence order.  SequenceEqual method determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

Code

//Your Input
int[] numSequence = { 1, 2, 3, 4, 5 };
//Check if they are in sequence or not
bool isInSequence = numSequence.SequenceEqual(Enumerable.Range(1, numSequence.Count()));

Above code will give the result as true if numbers are in proper sequence.

You also need to ensure that you have added the below namespace for Linq in your page

using System.Linq;

, ,

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 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

Null Conditional Operator in C# 6.0

Introduction:

In this article I am going to explain about one of the new feature introduced with C# 6.0 – Null Conditional Operator.

Explanation:

Null reference is one of the common exception which normally faced by most of the developers if you didn’t handled by adding proper checking for null values in code.

To resolve this null reference exception till now what we did was to add proper check condition for null values in code like given below

string firstname = null;
//Check if Firstname is null or not 
if(firstname != null)
{
     string res = firstname.Substring(0, 4);
}

Even though above code will works fine, we need to add additional code like if condition and all to safeguard the code from null reference exception. Wouldn’t it be nice if you have a single line of code which actually checks for null condition and the handles it.

With C# 6.0 they introduced a new operator called Null Conditional Operator (?). This will handles the above line of code in a single statement like given below

string firstname = null;
//Handle the null case using the operator(?) this wont throw null reference exception
string res = firstname?.Substring(0, 4);

Internally what the null conditional operator do is it will check for null before calling the following methods and if there is any null value the code execution will won’t proceed further and return the null value which subsequently stop the null reference exception from occurring.

Ex: In below code

string res = firstname?.Substring(0, 4);

Null conditional operator first check for null values in firstname and it will call the following method Substring method only if firstname is not null.

A word of caution while using null conditional operator is that you need to ensure that the variable you are assigning the result will be of nullable type

Ex:

The below code will throw an exception

DataTable dttable = new DataTable();
dttable = null;
int rowcount = dttable?.Rows.Count;

You need to make it nullable using nullableint to resolve the issue

DataTable dttable = new DataTable();
dttable = null;
int? rowcount = dttable?.Rows.Count;

, , , ,

Leave a comment