How to convert data table into JSON in C#?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string server = Request.QueryString["username"].ToString();
        string database = Request.QueryString["password"].ToString();
        SqlConnection con = new SqlConnection("database=" + database + ";server=" + server + "; integrated security=true;");

        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str, con);
        DataTable dt = new DataTable();
        da.Fill(dt);

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
        Dictionary<string, object> childRow;
        foreach (DataRow row in dt.Rows)
        {
            childRow = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                childRow.Add(col.ColumnName, row[col]);
            }
            parentRow.Add(childRow);
        }
        jsSerializer.Serialize(parentRow);
        Response.Write(jsSerializer.Serialize(parentRow));
    }
}
Share:

How to create Nested Grid-View in C#? Grid-View inside the Grid-View.

USE [kk]
GO

/****** Object:  Table [dbo].[emp]    Script Date: 02/14/2016 23:16:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[emp](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[salary] [decimal](18, 2) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

......................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NestedGridView.aspx.cs" Inherits="NestedGridView" %>

<!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>Nested GridView Example</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
.Grid td
{
background-color: White;
color: Black;
font-size: 10pt;
line-height: 200%;
}
.Grid th
{
background-color: Navy;
color: White;
font-size: 10pt;
line-height: 200%;
}
.ChildGrid td
{
background-color: Navy !important;
color: White;
font-size: 10pt;
line-height: 200%;
}
.ChildGrid th
{
background-color: Black !important;
color: White;
font-size: 10pt;
line-height: 200%;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function divexpandcollapse(divname) {
var img = "img" + divname;
if ($("#" + img).attr("src") == "images/plus.png") {
$("#" + img)
.closest("tr")
.after("<tr><td></td><td colspan = '100%'>" + $("#" + divname)
.html() + "</td></tr>");
$("#" + img).attr("src", "images/minus.png");
} else {
$("#" + img).closest("tr").next().remove();
$("#" + img).attr("src", "images/plus.png");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdViewCustomers" runat="server" AutoGenerateColumns="false" DataKeyNames="name"
OnRowDataBound="grdViewCustomers_OnRowDataBound" >
<Columns>
            <asp:BoundField  DataField="Name" HeaderText="Name" HeaderStyle-Width="100px" />
<asp:TemplateField  HeaderText="Salary" HeaderStyle-Width="100px" >
<ItemTemplate>
<%-- <a href="JavaScript:divexpandcollapse('div<%# Eval("name") %>');">
<img alt="Details" id="imgdiv<%# Eval("name") %>" src="images/plus.png" />
</a>
<div id="div<%# Eval("name") %>" style="display: none;">--%>
<asp:GridView ID="grdViewOrdersOfCustomer" Width="100%" runat="server"  AutoGenerateColumns="false" ShowHeader="false"
DataKeyNames="name" >
<Columns >

                                 
<asp:BoundField  DataField="Salary"  />

</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>


</Columns>
</asp:GridView>
</div>
<asp:Label ID="Label1" runat="server" style="font-weight: 700"
        Text="GrandTotal"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="Label2" runat="server" style="font-weight: 700" Text="Label"></asp:Label>
</form>
</body>
</html>
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class NestedGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
grdViewCustomers.DataSource = SelectData("SELECT distinct name FROM emp");
grdViewCustomers.DataBind();
        DataTable dt = SelectData("SELECT sum (salary) as total FROM emp");
        Label2.Text=dt.Rows[0]["total"].ToString();
}

private DataTable SelectData(string sqlQuery)
{
        string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, connectionString))
{
DataTable dt = new DataTable("emp");
sqlDataAdapter.Fill(dt);
return dt;
}
}

protected void grdViewCustomers_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerID = grdViewCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView grdViewOrdersOfCustomer = (GridView)e.Row.FindControl("grdViewOrdersOfCustomer");
grdViewOrdersOfCustomer.DataSource = SelectData("SELECT  name,salary FROM emp WHERE name='" + customerID + "'");
grdViewOrdersOfCustomer.DataBind();
}
}
}
Share:

How to create paging in Repeater control in C#?

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

public partial class Default4 : System.Web.UI.Page
{
    PagedDataSource pgsource = new PagedDataSource();
    int findex, lindex;
    DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindDataList();
        }

    }

    DataTable GetData()
    {
        SqlConnection connection = new SqlConnection(@"server=USER-PC\SQLEXPRESS;database=kk;integrated security =true;");
        connection.Open();
        SqlDataAdapter cmd = new SqlDataAdapter(" SELECT name from emp", connection);
        DataTable dtable = new DataTable();
        cmd.Fill(dtable);
        connection.Close();
        return dtable;

    }

    private void BindDataList()
    {
        DataTable dt = GetData();
        pgsource.DataSource = dt.DefaultView;
        pgsource.AllowPaging = true;
        pgsource.PageSize = 3;
        pgsource.CurrentPageIndex = CurrentPage;
        ViewState["totpage"] = pgsource.PageCount;
        lnkPrevious.Enabled = !pgsource.IsFirstPage;
        lnkNext.Enabled = !pgsource.IsLastPage;
        Repeater1.DataSource = pgsource;
        Repeater1.DataBind();
        doPaging();

    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        findex = CurrentPage - 3;
        if (CurrentPage > 3)
        {
            lindex = CurrentPage + 3;
        }
        else
        {
            lindex = 3;
        }
        if (lindex > Convert.ToInt32(ViewState["totpage"]))
        {
            lindex = Convert.ToInt32(ViewState["totpage"]);
            findex = lindex - 3;
        }
        if (findex < 0)
        {
            findex = 0;
        }
        for (int i = findex; i < lindex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

    }
    private int CurrentPage
    {
        get
        {
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return ((int)ViewState["CurrentPage"]);
            }
        }
        set
        {
         
            ViewState["CurrentPage"] = value;
        }
    }
    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        BindDataList();
    }
    protected void lnkNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        BindDataList();
    }
}
.............................................................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!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">
    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <div>
                <h2>
                    <a href="ShowImage.aspx">
                        <%# Eval("name") %></a>
                </h2>
            </div>
        </ItemTemplate>
    </asp:Repeater>
    <table style="width: 600px" border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td colspan="5">
            </td>
        </tr>
        <tr>
            <td align="center" valign="top" width="80">
                <asp:LinkButton ID="lnkPrevious" runat="server" OnClick="lnkPrevious_Click">Previous</asp:LinkButton>
            </td>
            <td align="center" valign="top" width="80">
                <asp:LinkButton ID="lnkNext" runat="server" OnClick="lnkNext_Click">Next</asp:LinkButton>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Share:

Tuesday, 16 February 2016

How to convert data table into JSON in C#?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string server = Request.QueryString["username"].ToString();
        string database = Request.QueryString["password"].ToString();
        SqlConnection con = new SqlConnection("database=" + database + ";server=" + server + "; integrated security=true;");

        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str, con);
        DataTable dt = new DataTable();
        da.Fill(dt);

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
        Dictionary<string, object> childRow;
        foreach (DataRow row in dt.Rows)
        {
            childRow = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                childRow.Add(col.ColumnName, row[col]);
            }
            parentRow.Add(childRow);
        }
        jsSerializer.Serialize(parentRow);
        Response.Write(jsSerializer.Serialize(parentRow));
    }
}

Sunday, 14 February 2016

How to create Nested Grid-View in C#? Grid-View inside the Grid-View.

USE [kk]
GO

/****** Object:  Table [dbo].[emp]    Script Date: 02/14/2016 23:16:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[emp](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[salary] [decimal](18, 2) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

......................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NestedGridView.aspx.cs" Inherits="NestedGridView" %>

<!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>Nested GridView Example</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
.Grid td
{
background-color: White;
color: Black;
font-size: 10pt;
line-height: 200%;
}
.Grid th
{
background-color: Navy;
color: White;
font-size: 10pt;
line-height: 200%;
}
.ChildGrid td
{
background-color: Navy !important;
color: White;
font-size: 10pt;
line-height: 200%;
}
.ChildGrid th
{
background-color: Black !important;
color: White;
font-size: 10pt;
line-height: 200%;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function divexpandcollapse(divname) {
var img = "img" + divname;
if ($("#" + img).attr("src") == "images/plus.png") {
$("#" + img)
.closest("tr")
.after("<tr><td></td><td colspan = '100%'>" + $("#" + divname)
.html() + "</td></tr>");
$("#" + img).attr("src", "images/minus.png");
} else {
$("#" + img).closest("tr").next().remove();
$("#" + img).attr("src", "images/plus.png");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdViewCustomers" runat="server" AutoGenerateColumns="false" DataKeyNames="name"
OnRowDataBound="grdViewCustomers_OnRowDataBound" >
<Columns>
            <asp:BoundField  DataField="Name" HeaderText="Name" HeaderStyle-Width="100px" />
<asp:TemplateField  HeaderText="Salary" HeaderStyle-Width="100px" >
<ItemTemplate>
<%-- <a href="JavaScript:divexpandcollapse('div<%# Eval("name") %>');">
<img alt="Details" id="imgdiv<%# Eval("name") %>" src="images/plus.png" />
</a>
<div id="div<%# Eval("name") %>" style="display: none;">--%>
<asp:GridView ID="grdViewOrdersOfCustomer" Width="100%" runat="server"  AutoGenerateColumns="false" ShowHeader="false"
DataKeyNames="name" >
<Columns >

                                 
<asp:BoundField  DataField="Salary"  />

</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>


</Columns>
</asp:GridView>
</div>
<asp:Label ID="Label1" runat="server" style="font-weight: 700"
        Text="GrandTotal"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="Label2" runat="server" style="font-weight: 700" Text="Label"></asp:Label>
</form>
</body>
</html>
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class NestedGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
grdViewCustomers.DataSource = SelectData("SELECT distinct name FROM emp");
grdViewCustomers.DataBind();
        DataTable dt = SelectData("SELECT sum (salary) as total FROM emp");
        Label2.Text=dt.Rows[0]["total"].ToString();
}

private DataTable SelectData(string sqlQuery)
{
        string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, connectionString))
{
DataTable dt = new DataTable("emp");
sqlDataAdapter.Fill(dt);
return dt;
}
}

protected void grdViewCustomers_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerID = grdViewCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView grdViewOrdersOfCustomer = (GridView)e.Row.FindControl("grdViewOrdersOfCustomer");
grdViewOrdersOfCustomer.DataSource = SelectData("SELECT  name,salary FROM emp WHERE name='" + customerID + "'");
grdViewOrdersOfCustomer.DataBind();
}
}
}

Sunday, 7 February 2016

How to create paging in Repeater control in C#?

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

public partial class Default4 : System.Web.UI.Page
{
    PagedDataSource pgsource = new PagedDataSource();
    int findex, lindex;
    DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindDataList();
        }

    }

    DataTable GetData()
    {
        SqlConnection connection = new SqlConnection(@"server=USER-PC\SQLEXPRESS;database=kk;integrated security =true;");
        connection.Open();
        SqlDataAdapter cmd = new SqlDataAdapter(" SELECT name from emp", connection);
        DataTable dtable = new DataTable();
        cmd.Fill(dtable);
        connection.Close();
        return dtable;

    }

    private void BindDataList()
    {
        DataTable dt = GetData();
        pgsource.DataSource = dt.DefaultView;
        pgsource.AllowPaging = true;
        pgsource.PageSize = 3;
        pgsource.CurrentPageIndex = CurrentPage;
        ViewState["totpage"] = pgsource.PageCount;
        lnkPrevious.Enabled = !pgsource.IsFirstPage;
        lnkNext.Enabled = !pgsource.IsLastPage;
        Repeater1.DataSource = pgsource;
        Repeater1.DataBind();
        doPaging();

    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        findex = CurrentPage - 3;
        if (CurrentPage > 3)
        {
            lindex = CurrentPage + 3;
        }
        else
        {
            lindex = 3;
        }
        if (lindex > Convert.ToInt32(ViewState["totpage"]))
        {
            lindex = Convert.ToInt32(ViewState["totpage"]);
            findex = lindex - 3;
        }
        if (findex < 0)
        {
            findex = 0;
        }
        for (int i = findex; i < lindex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

    }
    private int CurrentPage
    {
        get
        {
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return ((int)ViewState["CurrentPage"]);
            }
        }
        set
        {
         
            ViewState["CurrentPage"] = value;
        }
    }
    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        BindDataList();
    }
    protected void lnkNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        BindDataList();
    }
}
.............................................................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!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">
    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <div>
                <h2>
                    <a href="ShowImage.aspx">
                        <%# Eval("name") %></a>
                </h2>
            </div>
        </ItemTemplate>
    </asp:Repeater>
    <table style="width: 600px" border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td colspan="5">
            </td>
        </tr>
        <tr>
            <td align="center" valign="top" width="80">
                <asp:LinkButton ID="lnkPrevious" runat="server" OnClick="lnkPrevious_Click">Previous</asp:LinkButton>
            </td>
            <td align="center" valign="top" width="80">
                <asp:LinkButton ID="lnkNext" runat="server" OnClick="lnkNext_Click">Next</asp:LinkButton>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Popular

Total Pageviews

Archive