How to use JSON with ajax in ASP.NET?




In this article we learn how to use Ajax with Json in asp.net. It is very easy to call page method using ajax & Json. In this article we will call code behind method using jquery & Ajax. We can pass value or parameter from client end to server side using Json.




click Image to Enlarge it

Design(HTML Part):

<div>
Developer :
<asp:TextBox ID="txtDeveloper" runat="server"></asp:TextBox>
<input id="btnShow" type="button" value="Show Demo"
    onclick = "ShowJsonDemo()" />
</div>
When we click on the button btnShow, javaSript  function ShowJsonDemo will execute which will make Ajax call to GetJsonDemo Webmethod. In Javascript function we will pass textbox value as parameter to webmethod using Json.

Client Script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowJsonDemo() {
        $.ajax({
            type: "POST",
            url: "jSON.aspx/GetJsonDemo",
            data: '{developer: "' + $("#<%=txtDeveloper.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>


Code Behind:

[System.Web.Services.WebMethod]
    public static string GetJsonDemo(string developer)
    {
        return "First Application developed by " + developer +" on : "
            + DateTime.Now.ToString();
    }



Full Sample Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    function ShowJsonDemo() {
        $.ajax({
            type: "POST",
            url: "jSON.aspx/GetJsonDemo",
            data: '{developer: "' + $("#<%=txtDeveloper.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
Developer :
<asp:TextBox ID="txtDeveloper" runat="server"></asp:TextBox>
<input id="btnShow" type="button" value="Show Demo"
    onclick = "ShowJsonDemo()" />
</div>
    </form>
</body>
</html>

ASP.NET Code File:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class jSON : System.Web.UI.Page
{
    [System.Web.Services.WebMethod]
    public static string GetJsonDemo(string developer)
    {
        return "First Application developed by " + developer +" on : "
            + DateTime.Now.ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}


Import Data from Multiple Excelsheets to Multiple table in database in Asp.Net.


In this article I will explain how to Import data from Excel sheet with multiple worksheets to multiple table.

In this article I will Import data from Two worksheets to Two Table in SQL database.

 1.     Create a excel sheet with two worksheets, as given in example.
 2.     Now create two same tables in SQL database.
 3.     Keep in mind, Column name must be same in SQL Table & Excel Sheets.
 4.     Now write given code on button click event to import data from excel sheet to database tables.

Excel Sheet Example:




SQL Tables:

 

Employee Table                                                                 Dept Table

ASP.NET code to Import Data from Multiple Excel Sheets to Multiple Tables:

Add Following Namespaces:

using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

Write code on Button Click:

protected void Button1_Click(object sender, EventArgs e)
    {
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        string excelCon = "";
        string strFile = "C:\\Users\\Aman Sharma\\Desktop\\Test.xlsx";
        if (strFile.Trim().EndsWith(".xlsx"))
        {
            excelCon = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
        }
        else if (strFile.Trim().EndsWith(".xls"))
        {
            excelCon = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
        }

        objConn = new OleDbConnection(excelCon);

        objConn.Open();

        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        foreach (DataRow row in dt.Rows)
        {
            excelSheets[i] = row["TABLE_NAME"].ToString();
            i++;
        }

   //ifthere is empty sheet i.e. Sheet3 other dont decrease lenth by one.

        for (int j = 0; j < excelSheets.Length-1; j++)
        {           
            OleDbCommand cmd = new OleDbCommand("Select * from [" + excelSheets [j]+ "]",objConn);
          
            OleDbDataReader dReader;
            dReader = cmd.ExecuteReader();
            SqlBulkCopy sqlBulk = new SqlBulkCopy(con);
            if (j == 0)
            {
                sqlBulk.DestinationTableName = "Employee";
            }
            else if (j == 1)
            {
                sqlBulk.DestinationTableName = "Dept";
            }
            con.Open();
            sqlBulk.WriteToServer(dReader);
            con.Close();
          
        }
     objConn.Close();
    }

Delete record from Datagrid in windows application using c#


In this article we will learn how to delete item from Datagrid in window application using button inside DataGridView.

Follow these steps:

        1.  Add a webform in your application. Now add a datagrid to form.
  2.  No go to column property of Datagrid and click on Collectionto add button.

3.      No Click on Add button to add button.

          4.      Select DataGridViewButtonColumn option from Type drop down and click Add.

  5.      Now you can customize the properties. And click Ok.

Now Button is added to DataGridview


  6.    Now   Fill dataGridView and Write Code to delete record on CellClick event of datagrid:

       Database Table:













Fill DataGridview (C# code to fill DataGridview)  

private void Form3_Load(object sender, EventArgs e)
        {
            FillGrid(); 
        }

private void FillGrid()
        {
            DataTable dt = new System.Data.DataTable();
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Employee", con);
            adp.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

Now Write Code on CellClick Event of Gridview to Delete record:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check Index of Delete Button
            if (e.ColumnIndex == 0)
            {
                //Confirm Do you want to delete this record or not?
                DialogResult dlg = MessageBox.Show("Do you want to delete this item", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                if (dlg == DialogResult.Yes)
                {
                    int id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells["Id"].Value.ToString());
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
                    con.Open();
                    SqlCommand cmd = new SqlCommand("delete from Employee where Id=" + id, con);
                    cmd.ExecuteNonQuery();
                    con.Close();
      FillGrid();
                    MessageBox.Show("record Deleted successfully");
                }
            }


        }

Kategori

Kategori