Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, 12 May 2018

How to add the value of Barcode scanner in Textbox C#

Hi Guys,


Before doing the C# code we have to design out mobile windows application as per given below.

Above screen has one Text box and one label to display our output return by the scanner machine.

C# Code: 

public partial class MainPage : Form
    {
        public System.Windows.Forms.Timer tmrDelay;
        public MainPage()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (textBox1.Text.Trim().Length == 1)
                {
                    tmrDelay.Enabled = true;
                    tmrDelay.Tick += new EventHandler(tmrDelay_Tick);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            } 
           
        }

        void tmrDelay_Tick(object sender, EventArgs e)
        {
            try
            {
                tmrDelay.Enabled = false;
                string strCurrentString = textBox1.Text.Trim().ToString();
                if (strCurrentString != "")
                {
                    //Do something with the barcode entered 
                    lblOutput.Text="Output : "+strCurrentString;
                    textBox1.Text = "";
                }
                textBox1.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
       
        private void MainPage_Load(object sender, EventArgs e)
        {
            tmrDelay = new System.Windows.Forms.Timer(); 
            tmrDelay.Interval = 1000; 
            tmrDelay.Enabled = false;
        }

    }

After adding above code we will get the output as given below.

Thanks for reading :)

Wednesday, 29 July 2015

Calling web service from jquery ajax in asp.net

Calling web service from jquery ajax in asp.net

Arrange your file in solutions explorer in given below manner.

File Hierarchy

wcUser.asmx


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.IO;
using System.Text;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  
    [ScriptService]
    public class wcUser : System.Web.Services.WebService
    {
        public List<User> objUser;
        User user;

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }


        [WebMethod]
        public List<User> getUserList()
        {
            try
            {
                objUser = new List<User>();
                user= new User();
                user.Username = "Manoj";
                user.Password = "123";
                objUser.Add(user);
                user = new User();
                user.Username = "Prashant";
                user.Password = "456";
                objUser.Add(user);
            }
            catch { }
           
            return objUser;
        }
    }

Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script src="Scripts/Default.js" type="text/javascript"></script>
</head>
<body style="margin:10px">
    <form id="form1" runat="server" autocomplete="off">
    <div>
        <table border="0" class="table-condensed" cellpadding="0" cellspacing="0">
    <tr>
        <td>
        </td>
        <td>
            <asp:Button ID="btnWebService" CssClass="btn btn-danger" Text="Web Service" runat="server" />
        </td>
    </tr>
</table>
<hr />
<asp:GridView ID="gvUsers" runat="server" CssClass="table-condensed" HeaderStyle-BackColor="#3AC0F2"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
</asp:GridView>
    </div>
    <div>
        <table id="gvUsersTable" style="margin-left:10px;font-family:Courier New" class="table-condensed table-bordered">
           
        </table>
    </div>
    </form>
</body>
</html>

User.cs

public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

Default.js

$(function () {
    $("[id*=btnWebService]").bind("click", function () {
        $(this).val("Please Wait...");
        $("#gvUsersTable").empty();
        getUserListWebService();

        $(this).attr('disabled', 'disabled');

        return false;
    });
});


function getUserListWebService() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "WebService/wcUser.asmx/getUserList",
        data: "{}",
        dataType: "json",
        success: function (data) {
             if (data.d.length > 0) {
                $("#gvUsersTable").append("<tr style='background-color:#3AC0F2'><th>UserName</th> <th>Password</th><th>Delete</th></tr>");
                for (var i = 0; i < data.d.length; i++) {
                    $("#gvUsersTable").append("<tr><td>" + data.d[i].Username + "</td><td>" + data.d[i].Password + "</td><td align='center'>" + "<button style='background-color:#F99292;border:0px none;border-radius:50px' onclick='javascript:deleteUser(this.value);return false;' value='" + data.d[i].Username + "'>&times;</button>" + "</td></tr>");
                }
            }

            resetForm();
        },
        error: function (request, status, error) { alert(request); alert(status); alert(error); }
    });
}

function resetForm() {
    //After Load
    $("[id*=btnWebService]").removeAttr('disabled');
    $("[id*=btnWebService]").val("Web Service");
 }

Result:




Saturday, 25 July 2015

Insert Update Delete in ASP.NET using Jquery (Ajax/Json)

Create table UserList
Use following query to create table:

CREATE TABLE [dbo].[UserList](
       [UserName] [varchar](100) NULL,
       [Password] [varchar](100) NULL
)




Arrange your file in solutions explorer in given below manner.


Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script src="Scripts/Default.js" type="text/javascript"></script>
</head>
<body style="margin:10px">
    <form id="form1" runat="server" autocomplete="off">
    <div>
        <table border="0" class="table-condensed" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            Username:
        </td>
        <td>
            <asp:TextBox ID="txtUsername" runat="server" Text="" />
        </td>
    </tr>
    <tr>
        <td>
            Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button ID="btnSave" CssClass="btn btn-success" Text="Save" runat="server" />
            <asp:Button ID="btnMessage" CssClass="btn btn-info" Text="Load Data" runat="server" />
            <%--<input  type="button" value="click me" onclick="asyncServerCall(1);" />--%>
        </td>
    </tr>
</table>
<hr />
<asp:GridView ID="gvUsers" runat="server" CssClass="table-condensed" HeaderStyle-BackColor="#3AC0F2"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
</asp:GridView>
    </div>
    <div>
        <table id="gvUsersTable" style="margin-left:10px;font-family:Courier New" class="table-condensed table-bordered">
           
        </table>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

* Add below namespaces

using System.Web.Services;
using System.Web.Script.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;



 [WebMethod]
        [ScriptMethod]
        public static List<User> getUserData()
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            List<User> details = new List<User>();
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM UserList"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                       
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        sda.Fill(dt);
                        foreach (DataRow dtrow in dt.Rows)
                        {
                            User user = new User();
                            user.Username = dtrow["UserName"].ToString();
                            user.Password = dtrow["Password"].ToString();
                            details.Add(user);
                        }
                    }
                }
            }
            return details;
        }

         
        [WebMethod]
        [ScriptMethod]
        public static void SaveUser(User user)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO UserList VALUES(@Username, @Password)"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Username", user.Username);
                    cmd.Parameters.AddWithValue("@Password", user.Password);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        [WebMethod]
        [ScriptMethod]
        public static void deleteUser(string id)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("delete UserList where UserName=@userName"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@userName", id);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

User.cs

public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

Default.js

/*submit*/

//Save into Database
$(function () {
    $("[id*=btnSave]").bind("click", function () {
        var user = {};
        $(this).attr('disabled', 'disabled');
        $(this).val('Please Wait...');
        user.Username = $("[id*=txtUsername]").val();
        user.Password = $("[id*=txtPassword]").val();
        if (user.Username != "" && user.Password != "") {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveUser",
                data: '{user: ' + JSON.stringify(user) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("User has been added successfully.");
                    $("#gvUsersTable").empty();
                    getUserList();
                    resetForm();
                }
            });
        }
        else {
            alert("Please fill the details !");
            $(this).removeAttr('disabled');
            $(this).val('Save');
        }
        return false;
    });
});

//Reset Form
function resetForm() {
    //After Save
    $("[id*=btnSave]").removeAttr('disabled');
    $("[id*=btnSave]").val("Save");
    $("[id*=txtUsername]").val("");
    $("[id*=txtPassword]").val("");

    //After Load
    $("[id*=btnMessage]").removeAttr('disabled');
    $("[id*=btnMessage]").val("Load Data");
}

//Get grid by Button
$(function () {
    $("[id*=btnMessage]").bind("click", function () {
        $(this).val("Please Wait...");
        $("#gvUsersTable").empty();
        getUserList();

        $(this).attr('disabled', 'disabled');

        return false;
    });
});

//Load grid after window Load
$(document).ready(function () {
    $(window).load(function () {
        getUserList();
    });
});

//Get UserList and bind it into table
function getUserList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/getUserData",
        data: "{}",
        dataType: "json",
        success: function (data) {
            if (data.d.length > 0) {
                $("#gvUsersTable").append("<tr style='background-color:#3AC0F2'><th>UserName</th> <th>Password</th><th>Delete</th></tr>");
                for (var i = 0; i < data.d.length; i++) {
                    $("#gvUsersTable").append("<tr><td>" + data.d[i].Username + "</td><td>" + data.d[i].Password + "</td><td align='center'>" + "<button style='background-color:#F99292;border:0px none;border-radius:50px' onclick='javascript:deleteUser(this.value);return false;' value='" + data.d[i].Username + "'>&times;</button>" + "</td></tr>");
                }
            }
            resetForm();
        },
        error: function (result) {
            //alert("Error"+result);
        }
    });
}

//delete User from List
function deleteUser(id) {
    if (id == null || id == "") {
        alert("Id not Proper");
    }
    else {
        $.ajax({
            type: "POST",
            url: "Default.aspx/deleteUser",
            data: '{id: ' + JSON.stringify(id) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
               
                $("#gvUsersTable").empty();
                getUserList();
                alert("User has been deleted successfully.");
            }
        });
    }
    return false;
 }

Result