Sunday, April 26, 2015

Prevent Enter Click on Text Box using Java Script

When ever in your html if you click Enter key on a text box after typing your text the very next submit button is being hit automatically. Now not every time it causes problems but few times it creates an serious issue to the application.
So how to prevent this issue? With java script we can handle this very easily. Lets see how to do so?

Into a notepad document write down this line.

<input type='text' onkeydown="return (event.keyCode!=13);"/>

onkeydown="return (event.keyCode!=13);" 

This is the main code to prevent the Enter press within the textbox. 

Note: ASCII key of ENTER is 13.

Now save your document, run it in browser and check.

On line demo:

How to upload Database in Godaddy Server, explain with images

As a request form one of my follower I am writing this post about how to upload your Ms. SQL Server Database. Just follow my steps and in new few minutes your database will be on line in your Godaddy server.

Step 1:
First generate a script of your database with data (Schema & data).

Step 2:
Open your Godaddy server login into it and Go to Web Sites and Domain section. There is a link for Database (marked in pic) section. Click on it and you will be redirect to Database section.

Step 3:
Right now there is no database exists. So you have to create a new one. Click on the Add new database button and go to Add New Database page.

Step 4:
Here you have to enter your database name and  choose Microsoft SQL Server from Type drop down list.
Now its come to the user part. Here I don't have an exiting user so I have to create an user to access the database. So enter the user name and password for the user. You can generate the password for user also.
After all entry click on the OK button and if there is no issue you will be redirect to the previous page where you can see that you have a database with your given name and its user.  Now your database is created and you can add your tables, stored procedures, functions, views  and also insert data.

Note: make a note of the provided IP address and pin no. It will use in case of writing connection string in your web.config file.

Step 5:
To modify your database click on the webadmin link on the right side of your database. It will redirect you to a database management tool.

Step 6:
Click on the Tools section and within that on New Query button.

Step 7:
A new editor will be open for you to write sql query in it. Now copy and paste your local database script into this editor and click on the submit button.

Step 8:
After few minutes(as per your database size) your database will be on line. Now go back to your project. You have to change the connection string of you web.config file to attach this on line database.

Add the following connection string:

<add name="mlm_real_1050ConnectionString" connectionString="Data Source=<IP address>,<PIN No>; Initial Catalog=<Database name>;Network Library=DBMSSOCN;User ID=<User Name>;Password=<Password>;"      providerName="System.Data.SqlClient" />

Now upload your project and enjoy with your website.

Sunday, April 19, 2015

Import Export SQL Server database to Ms. Exel

Here in this post I will show you how to retrieve database table from Ms. Excel step by step with images. First create an excel file where all your data will be saved. 

Now saved this excel file into your drive and open Ms SQL Server management studio. Create a new database or you can do this in your existing database.

On clicking the button import a window will be opened with Data Source option. Choose Ms. Excel from here. 

Now click on the next button to choose Destination. 
Choose SQL Server and your database name from the drop down.

Now only few steps are ahead. Click on the Next button and go to Tables and Views Section. Here select the proper sheet of your excel. And change the name of table as you want.

By clicking on next few Next buttons you will get a success message with no of rows transferred.

Now cross check your database. And also your table which have been created during this process.

Now do it with yours and enjoy.


Get currency format using Google in ASP.NET

Many of times I have encountered by a vital question, "How to change 20000.00 to $20,000.00". This is nothing but a simple currency formatter. You can use either jquery or server side coding to show the currency in this format. Here in this post I will show you how to format the currency input from user in ASP.NET.

Format Currency using JQuery:
First start with JQuery. Google has provided a very simple way to format currency. You can find it out from here. Or you can follow this one.

To continue you have to download two js files. One is jquery.formatCurrency-1.4.0.js and second one is jquery.min.js. I have attached these js files with the code I have attached along with this post.

So lets start with sample coding. First create a new project and add a new page, named it whatever you want. Then add a new text box. Firstly we will do it with onBlur function of jquery, so we don't need any more extra button for showing our formatted currency.

Add those downloaded js files into your header section of web form. And the paste the following code into your page.

<script src="jquery.min.js"></script>
<script src="jquery.formatCurrency-1.4.0.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $('.text').focusout(function () {

Now copy the text box.

     <p>Currency Formatter</p>
     <asp:TextBox runat="server" ID="txtPrice" CssClass="text"></asp:TextBox>
     Show by Jquery: <span class="currencyLabel"></span>

Check the CssClass of text box. Its the thing by which formatCurrency() method is calling to format it to text box and also show the output value to a span.

Format Currency using C#:
I hope its clear to you how to format currency by JQuery, now lets see how to do this such using C#. Don't worry C# has an inbuilt function for this. For C# we are taking an extra button to display the output into a label.

<asp:TextBox ID="txtCurrency" runat="server"></asp:TextBox>
<asp:Button ID="btnChange" Text="Format" runat="server" OnClick="btnChange_Click"    />
<asp:Label ID="lblShow" runat="server"></asp:Label>

C# Code:

protected void btnChange_Click(object sender, EventArgs e)
    lblShow.Text = (Convert.ToDouble(txtCurrency.Text)).ToString("C2");

Make sure this method is only applicable to  data type like decimal and double. So you have to add a checking whether user input is bound to numbers.

Download the full source code here.

Friday, April 3, 2015

Jquery get method in MVC 4.0

In previous blog post I had discussed about how to post form data to back end, to controller and then to database, and here in this tutorial session I will show you how to get data asynchronously to server ie controller and from there to database. So how to do this? Honestly speaking its very simple, a few steps and its done.

So lets start by creating a new application, name it as you want. Create a new controller and a view against that controller.

We are going to implement a Login form, it may be any others also. Whatever the form is functionality is same. I choose a login form to show you choose according to your requirement. 

For login form we need two text boxes and one button. So design it quickly.


    <div id="login">
            <input type="text" id="email" /></p>
            <input type="password" id="password" /></p>
            <input type="button" value="Login" id="btnLogin" /></p>

Now add the jquery method.Before do any type of jquery operation add the jquery api. Here I am using Google api. You can also use it from different other sites(like or you can use it as your own.

<script src=""></script>

Now we can do coding of jquery.

On the btnLogin click we will call the get method and pass the variable to controller. Before we proceed we have to create a new controller where we can catch the data we are sending via jquery. 

So create  a new controller named Login.

Now write down these jquery code into your view page.

        function login() {
            var email = document.getElementById("email").value;
            var pass = document.getElementById("password").value;

                          email: email,
                          password: pass
                      }, function (data) {
                          if (data == "1") {
                              window.location.href = '../admin/dashboard';
                          else {
                              document.getElementById("lblMessage").innerHTML = data;

After this add a onclick properties to btnLogin. 

Now its turn for the Login controller.

public ActionResult CheckLogin(string email, string password)
      clsUser objUser = new clsUser();
      bool f = objUser.CheckLogin(email, password);
      if (f)
           Session["useremail"] = email;
           return Content("1");
           return Content("Please enter valid email & password !");

Here I have created a method CheckLogin under clsUser. In that method I am actually checking whether the user is valid or not. So lets take a look on that method.

public bool CheckLogin(string email, string pass)
    bool f = false;

    DataTable dt = new DataTable();
    string sql = "";
    sql = "select id from tblUser where email='"+email+"' and password = '"+pass+"'";
    dt = objServer.GetDataTable(sql);
    if (dt.Rows.Count == 1)
         f = true;
         f = false;
    return f;

Here I am using a simple ADO.NET code. Its not the right process to so. I have just used just because to make this short. I highly recommend to use parametrize query to do such thing.

Add a new connection string in web.config  to configure your server with this. And what else? your application is done. You have created it. Now test it and enjoy.

Download the full source code here.

Sunday, March 29, 2015

Highlight search text using Java Script

How to  highlight your search results instantly from your web page. As its more like searching an element or a phrase of word in your page or selected section. We will use Java Script to do this. Lets do how to do this.

Open any of those text editor you used. Write down your code or html to design your text portion in your page. Then come to the Java Script portion. Its playing the main role along with css.

As text I am putting the content of Kolkata, my city. You put your content or fetch back from your database. So you can test your application is running successfully or not.

<div id="search" name="search">
    <input name="query" id="query" type="text" size="30" maxlength="30" />
    <input name="searchit" type="button" value="Search" onclick="highlightSearch()" />
    <div id="searchtext">
                Kolkata /koʊlˈkɑːtɑː/, formerly Calcutta /kælˈkʌtə/, is the capital of    the Indian state of West Bengal.
                Located on the east bank of the Hooghly river, it is the principal commercial, cultural,
                and educational centre of East India, while the Port of Kolkata is India's oldest operating
                port as well as its sole major riverine port. As of 2011, the city had 4.5 million residents;
                the urban agglomeration, which comprises the city and its suburbs, was home to approximately
                14.1 million, making it the third-most populous metropolitan area in India. As of 2008,
                its economic output as measured by gross domestic product ranked third among South Asian cities, behind Mumbai and Delhi.


Now write down this java script function to do the trick.

function highlightSearch() {
      var text = document.getElementById("query").value;
      var query = new RegExp("(\\b" + text + "\\b)", "gim");
      var e = document.getElementById("searchtext").innerHTML;
      var enew = e.replace(/(<span>|<\/span>)/igm, "");
      document.getElementById("searchtext").innerHTML = enew;
      var newe = enew.replace(query, "<span>$1</span>");
      document.getElementById("searchtext").innerHTML = newe;

Now you must remember the importance of css to modify the text. So here is the css part to make the text highlighted.

#searchtext span {
    background-color: #FF9;
    color: #555;

div {
  padding: 10px;

Now run your program and test it. Enjoy..
Download the full source code here.

Friday, February 13, 2015

User Control in ASP.NET C#


In this post I will show you how to add UserControl to your .NET web application or web site with the back end in C#. Its a very basic thing to cover in .NET and I am sure many of you are aware of this. So those are not aware of the UserControl till now they have no need to worry because this article will cover the whole thing about UserControl.

What is the purpose to use UserControl?

Usually we use master page to set a template or something static in every page. Here we will do the same, but in a different way. Here we will add the controls in one page to make it as a whole one. This is the alternate process of master page and some time its better than the master page, because you can separate each section is a page  into a different control and code it as you do. 

Difference between Master page and UserControl

In master page concept you can put all the necessary control like say menu, login or registration, header, footer in one master page and in the slave page you just  inherit those and put the different data in the ContentPlaceHolder as per your requirement. And for that you have to code of all thing within one master page. How about this if you separate the all sections (menu, login or registration, header, footer) and just add as a control (like a button or a label) into your project. This is the UserControl concept. You create control for header, footer, login, register separately, and where ever you need just add the control. One extra thing you have to do is need to add a Register tag at the top of each page, because its a user created control, not an inbuilt one.

So lets see how to create a web page adding the controls. We will create a simple web page  to do this.

Create a new project and add a new web form, add a html table for the structuring the web page. Now add a new folder named control, here all the controls will be stores. 

Here add a new item, add Web User Control named it header.ascx.

Here you can design your header section. I have just add a H1 tag within a anchor tag to redirect it to insex page. If you can want you can code in C# just like another web page. You must remember it has functionality like any other web page, but it can't run alone like the master page. it will act as a section of a page and it does not content any form.


Header Section

Now put the footer section, same as like header section. Now put a demo section which will content code to make you understand better how it works. We will do a simple code to show a pop up box in a UserControl. So add another control in the control folder. 

Add a new asp button on this and on button click add this code.

Response.Write("alert message goes here.");

Now here is the question how to add these into your web page. Here is the solution.
On your web page write down these code at the top of the page after Page tag.

<%@ Register Src="~/Controls/header.ascx" TagPrefix="uc1" TagName="header" %>
<%@ Register Src="~/Controls/footer.ascx" TagPrefix="uc1" TagName="footer" %>
<%@ Register Src="~/Controls/demo.ascx" TagPrefix="uc1" TagName="demo" %>

and where you want to add the controls just put down these controls.

These are your controls, do whatever you want to do with these.

See the file attached for a better experience. Run your project and test your code.

Download full source code here.

Saturday, January 24, 2015

SQL Bulk copy from DataTable using XML

To copy data from DataTable or DataSet to SQL Server we need to use either foreach or for loop. It is OK when the count of rows is reasonable. But if the data is like 1 lakh or 1 core, then it is not possible to round the loop for such that time. Then what to do? A simple and easy way to follow is use XML. I am sure you all are more or less aware of this XML. Its a like the database with tags. Or I better to say its a database. It keeps data into a file with extension of  ".xml".

Our intention to convert the DataTable's data into an XML file and send it to server, where with the help of a stored procedure we will extract data and insert into the database table. So lets come see, how to do this...

First of all create a new database and create a new table, named it as you want. Database table structure will be like this.

Name NVarChar(255) not null
Adderss NVarChar(255) not null
Phone NvarChar(12) not null

OK, now we need to create a new DataTable  and put some data on it. Make sure your column and the database table's column are same.

DataTable dt = new DataTable();

dt.Rows.Add("Arkadeep", "Kolkata", "123456890");
dt.Rows.Add("Saikat", "Chennai", "99999999");

dt.Rows.Add("Sucheta", "Delhi", "9876543210");

Now you have to convert this DataTable into XML. To do this copy and paste the following code after the DataTable section. 

private static string ConvertToXML(DataTable dt)
      DataSet dsBuildSQL = new DataSet();
      StringBuilder sbSQL;
      StringWriter swSQL;
      string XMLformat;
           sbSQL = new StringBuilder();
           swSQL = new StringWriter(sbSQL);
           dsBuildSQL.Merge(dt, true, MissingSchemaAction.AddWithKey);
           dsBuildSQL.Tables[0].TableName = "DataTable";
           foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
               col.ColumnMapping = MappingType.Attribute;
           dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
           XMLformat = sbSQL.ToString();
           return XMLformat;
       catch (Exception sysException)
           throw sysException;

Call this method to convert the DataTable to XML. 

String xmlData = ConvertToXML(dt);

Now pass the value to the stored procedure like the following way.

SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ToString());
SqlCommand command = new SqlCommand("sp_InsertData '" + xmlData + "'", conn);

Now lets check the stored procedure sp_InsertData.

(@xmlString VARCHAR(MAX))

      DECLARE @xmlHandle INT
      DECLARE @stagingTable TABLE
         [Name]               VARCHAR(50),
         [Address]            VARCHAR(50),
         [Phone]              VARCHAR(50)
      EXEC sp_xml_preparedocument @xmlHandle output, @xmlString 

      INSERT INTO @stagingTable
      SELECT  [Name]    ,
      FROM  OPENXML (@xmlHandle, '/DataTable',1)
                        WITH ([Name]            varchar(50)       '@Name',
                                [Address]       varchar(50)       '@Address',
                                [Phone]         varchar(50)       '@Phone'

      INSERT INTO SampleData ([Name], [Address], [Phone])
            (SELECT [Name] , [Address],[Phone]FROM @stagingTable)
      EXEC sp_xml_removedocument @xmlHandle

Now run your project and after run this check your database table whether data has been inserted or not...