How to bind repeater inside the gridview using c#? Example.

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

<!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>
        <asp:HiddenField ID="HiddenField1" runat="server" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
            onrowcommand="GridView1_RowCommand">
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
        <asp:Label ID="lblid" runat="server" Text='<%#Eval("id") %>'></asp:Label>
            <asp:Label ID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
            <asp:LinkButton ID="lnkgrdid" runat="server" CommandName="grdid" CommandArgument='<%#Eval("id") %>'>Add Msg</asp:LinkButton>
            <br />
            <EmptyDataTemplate>
                <asp:Repeater ID="Repeater1" runat="server"
                    onitemcommand="Repeater1_ItemCommand">
                     <ItemTemplate>   <br />
                             <asp:Label ID="lblrptid" runat="server" Text='<%#Eval("id") %>'></asp:Label>

        <asp:Label ID="lblcity" runat="server" Text='<%#Eval("city") %>'></asp:Label>
        <asp:LinkButton ID="lnkid" runat="server" CommandName="save" CommandArgument='<%#Eval("id") %>'>save</asp:LinkButton>
   
        </ItemTemplate>
                </asp:Repeater>
            </EmptyDataTemplate>
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </div>
    </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;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"server=DESKTOP-OCBQF7H\SQLEXPRESS;database=lordshiva;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    { if(!IsPostBack)
        {
          bind();
        }

    }
    protected void bind()
    {
        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str,con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if(e.CommandName=="save")
        {
           // Repeater rpt = (Repeater)e.Item.FindControl("GridView1");
            string i = HiddenField1.Value;
            int index = Convert.ToInt32(i);


        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "grdid")
        {
            GridViewRow gr = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int i = gr.RowIndex;
            HiddenField1.Value = i.ToString();
            Repeater rpt = (Repeater)gr.FindControl("Repeater1");
            string str = "select * from employee";
            SqlDataAdapter da = new SqlDataAdapter(str, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            rpt.DataSource = ds;
            rpt.DataBind();
        }
    }
}
Share:

How to create date time clock using JavaScript? Example.

    <script type="text/javascript">

tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;

if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}

if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;

document.getElementById('clockbox').innerHTML=""+ndate+", "+tmonth[nmonth]+" , "+nyear+" "+nhour+":"+nmin+":"+nsec+ap+"";
}

window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>
<div id="clockbox"></div>
Share:

How to create dynamic image on button click in C#? Example.

Table tbldynamic = new Table();
        for (int i = 0; i < 5; i++)
        {
            TableCell tc = new TableCell();
            TableRow tr = new TableRow();
            Image _checkbox = new Image();
            _checkbox.ID = "chkDynamicCheckBox" + i;
            _checkbox.ImageUrl = "k4.jpeg";
            tc.Controls.Add(_checkbox);
            tr.Cells.Add(tc);
            tbldynamic.Rows.Add(tr);
        }
        Panel1.Controls.Add(tbldynamic);
        Panel1.Visible = true;

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

<!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 id="Head1" runat="server">
<title></title>
    <style type="text/css">
        .style1 {
            width: 30%;
            border-color: #FFCCFF;
            background-color: #FFCCCC;
        }
        .style2
        {
            width: 87px;
        }
    </style>
</head>
<body>
<form id="form2" runat="server">
<div>
    <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />

    <asp:Panel ID="Panel1" runat="server">
    <table align="center" class="style1">
        <tr>
            <td class="style2">
                Name</td>
            <td>
                <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
                City</td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
                &nbsp;</td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </td>
        </tr>
    </table>
    </asp:Panel>
 
</div>
</form>
</body>
</html>
Share:

How to find SUM using sub query in SQL Server?

select websiteId,status,EnquiryDate,sum(countname) as TotalCount
from
(
    SELECT Top 10
        count(d.EnqStatus) as countname,
        d.WebSiteID as websiteId,
d.EnquiryDate as EnquiryDate,
d.EnqStatus as status
    FROM Enquiry as d
    group by d.EnqStatus,d.Name,d.WebSiteID ,d.EnquiryDate
    order by count(d.EnqStatus) desc
)a
group by a.websiteId,a.status ,a.EnquiryDate having a.WebSiteID='1' and EnquiryDate between '2012-04-20 01:57:26.877'  and '2015-04-20 01:57:26.877'  
Share:

How to import excel data into database and display in GridView using C#?

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

<!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>Import Excel Data into GridView</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <br />
            <asp:HiddenField ID="Hiddenfield1" runat="server"></asp:HiddenField>
            <asp:Label ID="Label1" runat="server" Text="Has Header ?"></asp:Label>
            <asp:RadioButtonList ID="rbHDR" runat="server">
                <asp:ListItem Text="Yes" Value="Yes" Selected="True"></asp:ListItem>
                <asp:ListItem Text="No" Value="No"></asp:ListItem>
            </asp:RadioButtonList>
            <asp:GridView ID="GridView1" runat="server" OnPageIndexChanging="PageIndexChanging" AllowPaging="true">
            </asp:GridView>
        </div>
    </form>
</body>
</html>
------------------------------------------------------
using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string FolderPath = ConfigurationManager.AppSettings["FolderPath"];

            string FilePath = Server.MapPath(FolderPath + FileName);
            FileUpload1.SaveAs(FilePath);
            Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
        }
    }
    private void Import_To_Grid(string FilePath, string Extension, string isHDR)
    {
        string conStr="";
        switch (Extension)
        {
            case ".xls": //Excel 97-03
                conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07
                conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
        }
        conStr = String.Format(conStr, FilePath, isHDR);
        OleDbConnection connExcel = new OleDbConnection(conStr);
        OleDbCommand cmdExcel = new OleDbCommand();
        OleDbDataAdapter oda = new OleDbDataAdapter();
        DataTable dt = new DataTable(); 
        cmdExcel.Connection = connExcel;

        //Get the name of First Sheet
        connExcel.Open();
        DataTable dtExcelSchema;
        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
        connExcel.Close();

        //Read Data from First Sheet
        connExcel.Open();
        cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
        oda.SelectCommand = cmdExcel;
        oda.Fill(dt);
        for (int i = 0; i < dt.Rows.Count;i++ )
        {
                SqlConnection con = new SqlConnection(@"database=kk;server=Soham\SQLEXPRESS;integrated security=true;");
                string leadid = dt.Rows[i]["leadid"].ToString();
                string name = dt.Rows[i]["name"].ToString();
                string email = dt.Rows[i]["email"].ToString();
                int lead = Convert.ToInt32(dt.Rows[i]["leadid"].ToString());
                string str = "insert into employee(name,email,leadid) values ('" + name + "','" + email + "'," + lead + ")";
                con.Open();
                SqlCommand cmd = new SqlCommand(str, con);
                cmd.ExecuteNonQuery();
                con.Close();
        }
        connExcel.Close(); 
       //Bind Data to GridView
        GridView1.Caption = Path.GetFileName(FilePath); 
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
 
    protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        string FolderPath = ConfigurationManager.AppSettings["FolderPath"] ;
        string FileName = GridView1.Caption;
        string Extension = Path.GetExtension(FileName);
        string FilePath = Server.MapPath(FolderPath + FileName);

        Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);  
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();  
    }
}

----------------------------------
<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
  <appSettings>
    <add key ="FolderPath" value ="Files/"/>
  </appSettings >
  <connectionStrings>
    <add name ="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
    <add name ="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
  </connectionStrings > 
<system.web>
<!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
<compilation debug="true"/>
<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
<authentication mode="Windows"/>
<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
</system.web>
</configuration>

Share:

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:

How to create Auto Refresh pages in Asp .NET using C#?

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

<!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>
    <meta http-equiv="refresh" content="0.5">
    <%--content="30" is for 30 Seconds--%>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCount" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
.............................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MetaTag : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["count"]) == "")
                Session["count"] = 0;
            else
                Session["count"] = Convert.ToInt32(Session["count"]) + 1;
            lblCount.Text = Convert.ToString(Session["count"]) + " time page refresh";
            Response.Write("kul");
        }
    }
}

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

<!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 id="Head1" runat="server">
    <title></title>

    <script type="text/javascript" language="javascript">

        var idleInterval = setInterval("reloadPage()", 1000); // 30 Seconds

        function reloadPage() {
            location.reload();
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCount" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
...........................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JavaScript : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["count"]) == "")
                Session["count"] = 0;
            else
                Session["count"] = Convert.ToInt32(Session["count"]) + 1;
            lblCount.Text = Convert.ToString(Session["count"]) + " time page refresh";
        }
    }
}
..................................third...................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQuery.aspx.cs" Inherits="JQuery" %>

<!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 id="Head1" runat="server">
    <title></title>

    <script type="text/javascript" language="Javascript" 
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

    <script type="text/javascript" language="javascript">

        $(document).ready(function() {
            var idleInterval = setInterval("reloadPage()", 1000); // 30 Seconds
        })

        function reloadPage() {
            location.reload();
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCount" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JQuery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["count"]) == "")
                Session["count"] = 0;
            else
                Session["count"] = Convert.ToInt32(Session["count"]) + 1;
            lblCount.Text = Convert.ToString(Session["count"]) + " time page refresh";
        }
    }
}

Share:

Sunday, 8 May 2016

How to bind repeater inside the gridview using c#? Example.

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

<!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>
        <asp:HiddenField ID="HiddenField1" runat="server" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
            onrowcommand="GridView1_RowCommand">
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
        <asp:Label ID="lblid" runat="server" Text='<%#Eval("id") %>'></asp:Label>
            <asp:Label ID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
            <asp:LinkButton ID="lnkgrdid" runat="server" CommandName="grdid" CommandArgument='<%#Eval("id") %>'>Add Msg</asp:LinkButton>
            <br />
            <EmptyDataTemplate>
                <asp:Repeater ID="Repeater1" runat="server"
                    onitemcommand="Repeater1_ItemCommand">
                     <ItemTemplate>   <br />
                             <asp:Label ID="lblrptid" runat="server" Text='<%#Eval("id") %>'></asp:Label>

        <asp:Label ID="lblcity" runat="server" Text='<%#Eval("city") %>'></asp:Label>
        <asp:LinkButton ID="lnkid" runat="server" CommandName="save" CommandArgument='<%#Eval("id") %>'>save</asp:LinkButton>
   
        </ItemTemplate>
                </asp:Repeater>
            </EmptyDataTemplate>
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </div>
    </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;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"server=DESKTOP-OCBQF7H\SQLEXPRESS;database=lordshiva;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    { if(!IsPostBack)
        {
          bind();
        }

    }
    protected void bind()
    {
        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str,con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if(e.CommandName=="save")
        {
           // Repeater rpt = (Repeater)e.Item.FindControl("GridView1");
            string i = HiddenField1.Value;
            int index = Convert.ToInt32(i);


        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "grdid")
        {
            GridViewRow gr = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int i = gr.RowIndex;
            HiddenField1.Value = i.ToString();
            Repeater rpt = (Repeater)gr.FindControl("Repeater1");
            string str = "select * from employee";
            SqlDataAdapter da = new SqlDataAdapter(str, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            rpt.DataSource = ds;
            rpt.DataBind();
        }
    }
}

Tuesday, 26 April 2016

How to create date time clock using JavaScript? Example.

    <script type="text/javascript">

tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
if(nyear<1000) nyear+=1900;
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;

if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}

if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;

document.getElementById('clockbox').innerHTML=""+ndate+", "+tmonth[nmonth]+" , "+nyear+" "+nhour+":"+nmin+":"+nsec+ap+"";
}

window.onload=function(){
GetClock();
setInterval(GetClock,1000);
}
</script>
<div id="clockbox"></div>

Wednesday, 13 April 2016

How to create dynamic image on button click in C#? Example.

Table tbldynamic = new Table();
        for (int i = 0; i < 5; i++)
        {
            TableCell tc = new TableCell();
            TableRow tr = new TableRow();
            Image _checkbox = new Image();
            _checkbox.ID = "chkDynamicCheckBox" + i;
            _checkbox.ImageUrl = "k4.jpeg";
            tc.Controls.Add(_checkbox);
            tr.Cells.Add(tc);
            tbldynamic.Rows.Add(tr);
        }
        Panel1.Controls.Add(tbldynamic);
        Panel1.Visible = true;

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

<!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 id="Head1" runat="server">
<title></title>
    <style type="text/css">
        .style1 {
            width: 30%;
            border-color: #FFCCFF;
            background-color: #FFCCCC;
        }
        .style2
        {
            width: 87px;
        }
    </style>
</head>
<body>
<form id="form2" runat="server">
<div>
    <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />

    <asp:Panel ID="Panel1" runat="server">
    <table align="center" class="style1">
        <tr>
            <td class="style2">
                Name</td>
            <td>
                <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
                City</td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
                &nbsp;</td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Button" />
            </td>
        </tr>
    </table>
    </asp:Panel>
 
</div>
</form>
</body>
</html>

Monday, 21 March 2016

How to find SUM using sub query in SQL Server?

select websiteId,status,EnquiryDate,sum(countname) as TotalCount
from
(
    SELECT Top 10
        count(d.EnqStatus) as countname,
        d.WebSiteID as websiteId,
d.EnquiryDate as EnquiryDate,
d.EnqStatus as status
    FROM Enquiry as d
    group by d.EnqStatus,d.Name,d.WebSiteID ,d.EnquiryDate
    order by count(d.EnqStatus) desc
)a
group by a.websiteId,a.status ,a.EnquiryDate having a.WebSiteID='1' and EnquiryDate between '2012-04-20 01:57:26.877'  and '2015-04-20 01:57:26.877'  

Wednesday, 9 March 2016

How to import excel data into database and display in GridView using C#?

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

<!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>Import Excel Data into GridView</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <br />
            <asp:HiddenField ID="Hiddenfield1" runat="server"></asp:HiddenField>
            <asp:Label ID="Label1" runat="server" Text="Has Header ?"></asp:Label>
            <asp:RadioButtonList ID="rbHDR" runat="server">
                <asp:ListItem Text="Yes" Value="Yes" Selected="True"></asp:ListItem>
                <asp:ListItem Text="No" Value="No"></asp:ListItem>
            </asp:RadioButtonList>
            <asp:GridView ID="GridView1" runat="server" OnPageIndexChanging="PageIndexChanging" AllowPaging="true">
            </asp:GridView>
        </div>
    </form>
</body>
</html>
------------------------------------------------------
using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string FolderPath = ConfigurationManager.AppSettings["FolderPath"];

            string FilePath = Server.MapPath(FolderPath + FileName);
            FileUpload1.SaveAs(FilePath);
            Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
        }
    }
    private void Import_To_Grid(string FilePath, string Extension, string isHDR)
    {
        string conStr="";
        switch (Extension)
        {
            case ".xls": //Excel 97-03
                conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07
                conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
        }
        conStr = String.Format(conStr, FilePath, isHDR);
        OleDbConnection connExcel = new OleDbConnection(conStr);
        OleDbCommand cmdExcel = new OleDbCommand();
        OleDbDataAdapter oda = new OleDbDataAdapter();
        DataTable dt = new DataTable(); 
        cmdExcel.Connection = connExcel;

        //Get the name of First Sheet
        connExcel.Open();
        DataTable dtExcelSchema;
        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
        connExcel.Close();

        //Read Data from First Sheet
        connExcel.Open();
        cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
        oda.SelectCommand = cmdExcel;
        oda.Fill(dt);
        for (int i = 0; i < dt.Rows.Count;i++ )
        {
                SqlConnection con = new SqlConnection(@"database=kk;server=Soham\SQLEXPRESS;integrated security=true;");
                string leadid = dt.Rows[i]["leadid"].ToString();
                string name = dt.Rows[i]["name"].ToString();
                string email = dt.Rows[i]["email"].ToString();
                int lead = Convert.ToInt32(dt.Rows[i]["leadid"].ToString());
                string str = "insert into employee(name,email,leadid) values ('" + name + "','" + email + "'," + lead + ")";
                con.Open();
                SqlCommand cmd = new SqlCommand(str, con);
                cmd.ExecuteNonQuery();
                con.Close();
        }
        connExcel.Close(); 
       //Bind Data to GridView
        GridView1.Caption = Path.GetFileName(FilePath); 
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
 
    protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        string FolderPath = ConfigurationManager.AppSettings["FolderPath"] ;
        string FileName = GridView1.Caption;
        string Extension = Path.GetExtension(FileName);
        string FilePath = Server.MapPath(FolderPath + FileName);

        Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);  
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();  
    }
}

----------------------------------
<?xml version="1.0"?>
<!-- 
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
  <appSettings>
    <add key ="FolderPath" value ="Files/"/>
  </appSettings >
  <connectionStrings>
    <add name ="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
    <add name ="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
  </connectionStrings > 
<system.web>
<!-- 
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
        -->
<compilation debug="true"/>
<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
<authentication mode="Windows"/>
<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
</system.web>
</configuration>

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>

Tuesday, 12 January 2016

How to create Auto Refresh pages in Asp .NET using C#?

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

<!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>
    <meta http-equiv="refresh" content="0.5">
    <%--content="30" is for 30 Seconds--%>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCount" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
.............................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MetaTag : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["count"]) == "")
                Session["count"] = 0;
            else
                Session["count"] = Convert.ToInt32(Session["count"]) + 1;
            lblCount.Text = Convert.ToString(Session["count"]) + " time page refresh";
            Response.Write("kul");
        }
    }
}

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

<!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 id="Head1" runat="server">
    <title></title>

    <script type="text/javascript" language="javascript">

        var idleInterval = setInterval("reloadPage()", 1000); // 30 Seconds

        function reloadPage() {
            location.reload();
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCount" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
...........................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JavaScript : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["count"]) == "")
                Session["count"] = 0;
            else
                Session["count"] = Convert.ToInt32(Session["count"]) + 1;
            lblCount.Text = Convert.ToString(Session["count"]) + " time page refresh";
        }
    }
}
..................................third...................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQuery.aspx.cs" Inherits="JQuery" %>

<!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 id="Head1" runat="server">
    <title></title>

    <script type="text/javascript" language="Javascript" 
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

    <script type="text/javascript" language="javascript">

        $(document).ready(function() {
            var idleInterval = setInterval("reloadPage()", 1000); // 30 Seconds
        })

        function reloadPage() {
            location.reload();
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCount" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JQuery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["count"]) == "")
                Session["count"] = 0;
            else
                Session["count"] = Convert.ToInt32(Session["count"]) + 1;
            lblCount.Text = Convert.ToString(Session["count"]) + " time page refresh";
        }
    }
}

Popular

Total Pageviews

Archive