Pages

Sunday, 29 April 2012

How to Write code for Paging in Grid view

----->>take one datalist for Paging



<asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" RepeatColumns="0"
                        OnItemCommand="dlPaging_ItemCommand" OnItemDataBound="dlPaging_ItemDataBound">
                        <ItemTemplate>
                            <table>
                                <tr>
                                    <td>
                                        <asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument="<%# Container.DataItem %>"
                                            Text='<%# Container.DataItem %>' CommandName="lnkbtnPaging" CssClass="button1"></asp:LinkButton>
                                    </td>
                                    <td width="2">
                                    </td>
                                </tr>
                            </table>
                        </ItemTemplate>
                    </asp:DataList>

----->>write C# code for paging


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class people : System.Web.UI.Page
{
    double rowCount;
    string count = "";
    string cname = "";
    string queryCount;
    double pageNo;
    int pgNo;
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlAnchor ach = (HtmlAnchor)Master.FindControl("b1");
        ach.Attributes.Add("class", "activ");
        if (!Page.IsPostBack)
        {
            if (Session["Userid"] != null)
            {
                Panel p1 = (Panel)Master.FindControl("WelcomePanel");
                p1.Visible = true;
                Panel p2 = (Panel)Master.FindControl("signpanel");
                p2.Visible = false;
                Label l1 = (Label)Master.FindControl("lblName");
                l1.Text = Session["name"].ToString();
            }
            else
            {
                Panel p1 = (Panel)Master.FindControl("WelcomePanel");
                p1.Visible = false ;
                Panel p2 = (Panel)Master.FindControl("signpanel");
                p2.Visible = true;
            }
            getpeopleadds();
            getpeoples();
            DisplayCompanyDetails();
        }
     
         
     
    }
    public int CurrentPage
    {

        get
        {

            if (this.ViewState["CurrentPage"] == null)
                return 0;
            else
                return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
        }
        set
        {
            this.ViewState["CurrentPage"] = value;
        }
    }

    private void DisplayCompanyDetails()
    {
        string cn = "";
        string qry = "";
        int start = Convert.ToInt32(CurrentPage * 3 + 1);
        int end = start + 3;
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();


        //qry = "set  sql_select_limit=40;select * from Directory where Status='Y' order by  Cid limit " + start + " ," + end;
        qry = "select * from( SELECT *, ROW_NUMBER() OVER (ORDER BY PeopleId desc) as row FROM Peoples ) a WHERE Status='Y' and row >=" + start + " and row <" + end;




        SqlCommand cmd = new SqlCommand(qry, con);
        con.Open();
        cmd.ExecuteNonQuery();
        SqlDataAdapter dataAdapter = new SqlDataAdapter();

        dataAdapter.SelectCommand = cmd;
        dataAdapter.Fill(ds);
        SqlCommand cmd1 = new SqlCommand("GetCount", con);
        cmd1.CommandType = CommandType.StoredProcedure;

        rowCount =Convert.ToInt32( cmd1.ExecuteScalar());
        dataAdapter.Dispose();
        con.Close();



        dt = ds.Tables[0];
        if (dt.Rows.Count > 0)
        {
            grdCategory .DataSource = dt;
            grdCategory.DataBind();
            dlPaging.Visible = true;
            doPaging();
        }
        else
        {
            lnkbtnNext.Visible = false;
            lnkbtnPrevious.Visible = true ;
            dlPaging.Visible = true ;
        }
    }

    private void doPaging()
    {
        pageNo = Math.Floor(rowCount / 3);
        if (pageNo != 0 && rowCount > 3)
        {
            pageNo = pageNo + 1;
        }
        else
        {
            pageNo = pageNo;
        }


        pgNo = Convert.ToInt32(pageNo);
        if (pgNo == 0)

            lnkbtnNext.Visible = false;
        ArrayList arr = Return_Pagination_Link(pgNo, 3, CurrentPage);

        if (rowCount > 1)
        {
            dlPaging.Visible = true;
            dlPaging.DataSource = arr;
            dlPaging.DataBind();

        }
        else
        {
            dlPaging.Visible = false;
        }

        if (CurrentPage == 0)
        {
            if (CurrentPage == (pgNo - 1))
            {
                dlPaging.Visible = false;
                lnkbtnNext.Visible = false;
            }

            lnkbtnPrevious.Visible = false;
        }

        if (CurrentPage < pageNo)

            lnkbtnNext.Visible = true;
        if (CurrentPage == (pageNo - 1))
        {
            lnkbtnNext.Visible = false;
        }

    }
    protected void lnkbtnPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        DisplayCompanyDetails();
    }


    protected void lnkbtnNext_Click(object sender, EventArgs e)
    {

        CurrentPage += 1;
        lnkbtnPrevious.Visible = true;
        DisplayCompanyDetails();
    }


    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("lnkbtnPaging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString()) - 1;
            lnkbtnPrevious.Visible = true;

            DisplayCompanyDetails();
            //DisplayCompanyDetails1();

        }
    }
    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        if (int.Parse(lnkbtnPage.CommandArgument.ToString()) - 1 == CurrentPage)
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Font.Bold = false;
            lnkbtnPage.ForeColor = System.Drawing.Color.OrangeRed;
         

        }
    }
    public ArrayList Return_Pagination_Link(int TotalPages, int Total_Links, int SelectedPage)
    {
        int i = 1;
        ArrayList arr = new ArrayList();
        if (TotalPages < Total_Links)
        {

            for (i = 1; i <= TotalPages; i++)
            {

                arr.Add(i);

            }

        }
        else
        {

            int startindex = SelectedPage;
            int lowerbound = startindex - (Total_Links / 2);
            int upperbound = startindex + (Total_Links / 2);

            if (lowerbound < 1)
            {
                //calculate the difference and increment the upper bound
                upperbound = upperbound + (1 - lowerbound);
                lowerbound = 1;
            }
            //if upperbound is greater than total page is
            if (upperbound > TotalPages)
            {
                //calculate the difference and decrement the lower bound
                lowerbound = lowerbound - (upperbound - TotalPages);
                upperbound = TotalPages;
            }
            for (i = lowerbound; i <= upperbound; i++)
            {
                arr.Add(i);
            }
        }
        return arr;
    }



Bind the data to nested grid view to the main grid view Row command event


   
<%@ Import Namespace="System.Data" %> <%@ Page Language="C#" AutoEventWireup="false" %> <script language="C#" runat="server"> void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { GridView gv = (GridView)sender; Int32 rowIndex = Convert.ToInt32(e.CommandArgument.ToString()); switch (e.CommandName) { case "Select": TextBox tb = gv.HeaderRow.FindControl("txtHeaderValue") as TextBox; lblHeaderValue.Text = "In the header textbox you entered: " + tb.Text; GridView childgv = (GridView)gv.Rows[rowIndex].FindControl("ChildGridView1"); if (childgv != null) { childgv.Visible = !childgv.Visible; ObjectDataSource odsOrders = (ObjectDataSource)gv.Rows[rowIndex].FindControl("odsOrders"); odsOrders.SelectParameters["CustomerID"].DefaultValue = gv.DataKeys[rowIndex][0].ToString(); DetailsView detV = (DetailsView)gv.Rows[rowIndex].FindControl("detvOrder"); if (detV != null) detV.Visible = childgv.Visible; } break; } } void ChildGridView_RowCommand(object sender, GridViewCommandEventArgs e) { GridView gv = (GridView)sender; Int32 rowIndex = Convert.ToInt32(e.CommandArgument.ToString()); switch (e.CommandName) { case "Select": DetailsView detV = (DetailsView)gv.Parent.FindControl("detvOrder"); if (detV != null) { ObjectDataSource odsOrders = (ObjectDataSource)gv.Parent.FindControl("odsOrderDetails"); odsOrders.SelectParameters["OrderId"].DefaultValue = gv.DataKeys[rowIndex][0].ToString(); } break; } } protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { GridViewRow grvrow = e.Row; Table tbl = new Table(); TableRow row = new TableRow(); TableCell[] aTD = new TableCell[grvrow.Cells.Count]; grvrow.Cells.CopyTo(aTD, 0); grvrow.Cells.Clear(); row.Cells.AddRange(aTD); tbl.Rows.Add(row); //second row row = new TableRow(); TableCell cell = new TableCell(); cell.ColumnSpan = aTD.Length; row.Cells.Add(cell); Label lbl = new Label(); lbl.Text = "This section contains a new header line that was added while handling the RowCreated event to manipulate the header row." + " Enter a value in this textbox then I will grab it and display while handling the select command"; cell.Controls.Add(lbl); TextBox tb = new TextBox(); tb.Text = "Enter a value" ; tb.ID = "txtHeaderValue"; cell.Controls.Add(tb); tbl.Rows.Add(row); //create a new cell within the gridview row TableCell cellGRV = new TableCell(); cellGRV.ColumnSpan = aTD.Length; grvrow.Cells.Add(cellGRV); cellGRV.Controls.Add(tbl); } } protected void ChildGridView1_SelectedIndexChanged(object sender, EventArgs e) { GridView1.SelectedRow.FindControl("detvOrder").Visible = !GridView1.SelectedRow.FindControl("detvOrder").Visible; } </script> <asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent"> <div style="width: 750px;"> <h2> Parent-Child GridViews using show/hide rows within the same table</h2> <p> Click on the arrow icon in front of a record to toggle the view between detail and summary.</p> <asp:Label id="lblHeaderValue" runat="Server"></asp:Label> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="False" OnRowCommand ="GridView1_RowCommand" DataKeyNames="CustomerID" DataSourceID="odsCustomers" AutoGenerateColumns="false" CssClass="NestedGridView1Style" OnRowCreated ="GridView1_RowCreated"> <SelectedRowStyle CssClass="Green" /> <HeaderStyle CssClass="Pink" /> <Columns> <asp:ButtonField ButtonType="Image" ImageUrl="~/App_Themes/WEBSWAPP/images/arrow.gif" CommandName="Select" Text="Click here to toggle the display of the orders list for this customer" /> <asp:TemplateField> <HeaderTemplate> <table cellpadding="2" cellspacing="0" border="0" width="860px"> <!-- this row has the parent grid --> <tr> <td width="660px"> Company Name</td> <td width="100px"> City</td> <td width="100px"> Country</td> </tr> </table> </HeaderTemplate> <ItemTemplate> <table border="0" cellpadding="2" cellspacing="0" width="860px"> <!-- this row has the parent grid --> <tr> <td width="660px"> <asp:Label ID="lblCompanyName" runat="server" Text='<%# Eval("CompanyName") %>'></asp:Label> </td> <td width="100px"> <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label> </td> <td width="100px"> <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label> </td> </tr> <!-- this row has the child grid and its details view--> <tr> <td colspan="3"> <table border="0" cellpadding="3" cellspacing="0" width="100%"> <tr> <!-- this cell has the list of orders for the selected customer --> <td> <asp:GridView ID="ChildGridView1" runat="server" DataKeyNames="OrderID" Visible="False" DataSourceID="odsOrders" AutoGenerateColumns="False" CssClass="GridView1ChildStyle" OnRowCommand="ChildGridView_RowCommand"> <SelectedRowStyle CssClass="Blue" /> <HeaderStyle CssClass="Header" /> <Columns> <asp:CommandField ShowEditButton="True" /> <asp:TemplateField HeaderText="Order Date"> <EditItemTemplate> <asp:TextBox ID="txtOrderDate" runat="server" Text='<%# Bind("OrderDate", "{0:d}") %>' Width="70px"></asp:TextBox> <asp:CompareValidator ID="valComp1" ValueToCompare="01/01/2020" ControlToValidate="txtOrderDate" Operator="LessThan" Type="Date" runat="server" Display="None" ErrorMessage="A valid date must be before January 01 2020" /> <asp:CompareValidator ID="valComp2" ValueToCompare="01/01/1980" ControlToValidate="txtOrderDate" Operator="GreaterThan" Type="Date" runat="server" Display="None" ErrorMessage="Invalid Date: A valid date must be after January 01 1980" /> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("OrderDate", "{0:d}") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Shipped Date"> <EditItemTemplate> <asp:TextBox ID="txtShippedDate" runat="server" Text='<%# Bind("ShippedDate", "{0:d}") %>' Width="70px"></asp:TextBox> <asp:CompareValidator ID="valComp3" ValueToCompare="01/01/2020" ControlToValidate="txtShippedDate" Operator="LessThan" Type="Date" runat="server" Display="None" ErrorMessage="A valid date must be before January 01 2020" /> <asp:CompareValidator ID="valComp4" ValueToCompare="01/01/1980" ControlToValidate="txtShippedDate" Operator="GreaterThan" Type="Date" runat="server" Display="None" ErrorMessage="Invalid Date: A valid date must be after January 01 1980" /> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Eval("ShippedDate", "{0:d}") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Ship Name"> <EditItemTemplate> <asp:TextBox ID="txtShipName" runat="server" Text='<%# Bind("ShipName") %>' Width="150px" MaxLength="35"></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("ShipName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Freight"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Freight", "{0:c}") %>' Width="70px"></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("Freight", "{0:c}") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:ButtonField ButtonType="Image" ImageUrl="~/App_Themes/WEBSWAPP/images/arrow.gif" CommandName="Select" Text="Click here to toggle the display of the detailed products on this order" /> </Columns> </asp:GridView> </td> <!--This cell has the order detail --> <td> <asp:DetailsView ID="detvOrder" runat="server" DataSourceID="odsOrderDetails" AllowPaging="True" DataKeyNames="OrderID,ProductID" AutoGenerateRows="false" > <FieldHeaderStyle CssClass="DetailsView1Header" /> <HeaderStyle CssClass="Header" /> <HeaderTemplate> <p> Order Details</p> </HeaderTemplate> <Fields> <asp:BoundField HeaderText="Order ID" DataField ="OrderID"/> <asp:BoundField DataField="ProductName" HeaderText="Product Name" /> <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" DataFormatString="{0:c}" HtmlEncode="False" /> <asp:BoundField DataField="Quantity" HeaderText="Quantity" DataFormatString="{0:#}" HtmlEncode="False" /> <asp:BoundField DataField="Discount" HeaderText="Discount" DataFormatString="{0:c}" HtmlEncode="False" /> <asp:BoundField DataField="ExtendedPrice" HeaderText="Extended Price" DataFormatString="{0:c}" HtmlEncode="False" /> <asp:CommandField ShowInsertButton ="true" /> </Fields> </asp:DetailsView> </td> </tr> </table> <asp:ObjectDataSource ID="odsOrderDetails" runat="server" SelectMethod="CustomerOrderDetails" TypeName="WEBSWAPP_BLL.Demos"> <SelectParameters> <asp:Parameter Name="OrderId" DefaultValue="0" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> <asp:ObjectDataSource ID="odsOrders" runat="server" SelectMethod="OrdersForCustomer" TypeName="WEBSWAPP_BLL.Demos" OldValuesParameterFormatString="original_{0}" UpdateMethod="UpdateOrder"> <SelectParameters> <asp:Parameter Name="CustomerID" DefaultValue="0" Type="string" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="OrderID" Type="Int32" /> <asp:Parameter Name="OrderDate" Type="DateTime" /> <asp:Parameter Name="ShippedDate" Type="DateTime" /> <asp:Parameter Name="ShipName" Type="String" /> <asp:Parameter Name="Freight" Type="String" /> </UpdateParameters> </asp:ObjectDataSource> </td> </tr> </table> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:ObjectDataSource ID="odsCustomers" runat="server" SelectMethod="Customers" TypeName="WEBSWAPP_BLL.Demos"> </asp:ObjectDataSource> <asp:Label ID="lblStatus" runat="server"></asp:Label> </div> </asp:Content>

How to Bind Data in Nested Gridview using Row Command Event


<ItemTemplate>
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("name") %>'></asp:Label>
  <asp:LinkButton ID="linkButton1" CommandName="select" runat="server" Text="Select" />
</ItemTemplate>
 
and Implement the RowCommand Event:
 
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "select")
  {
    GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
 
    GridView Grid2 = (GridView)row.FindControl("NestedGrid");
 
    //Neste GridDAta
 
    Response.Write("----------Nested Grid Data-------------");
    foreach (GridViewRow Childrow in Grid2.Rows)
    {
      string stid = ((Label)Childrow.FindControl("Label1")).Text;
      string name = ((Label)Childrow.FindControl("Label2")).Text;
 
      Response.Write(stid);
      Response.Write("<br>");
      Response.Write(name);
    }
  }
}
 

Monday, 16 April 2012

How to Use Collapse Panel in ajax


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!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>Collapsible Panel Example</title>
<style type="text/css">
.pnlCSS{
font-weight: bold;
cursor: pointer;
border: solid 1px #c0c0c0;
width:30%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScriptManager1" runat="server">
</ajax:ToolkitScriptManager>
<div>
<asp:Panel ID="pnlClick" runat="server" CssClass="pnlCSS">
<div style="background-image:url('green_bg.gif'); height:30px; vertical-align:middle">
<div style="float:left; color:White;padding:5px 5px 0 0">
Collapsible Panel
</div>
<div style="float:right; color:White; padding:5px 5px 0 0">
<asp:Label ID="lblMessage" runat="server" Text="Label"/>
<asp:Image ID="imgArrows" runat="server" />
</div>
<div style="clear:both"></div>
</div>
</asp:Panel>
<asp:Panel ID="pnlCollapsable" runat="server" Height="0" CssClass="pnlCSS">
<table align="center" width="100%">
<tr>
<td></td>
<td>
<b>Registration Form</b>
</td>
</tr>
<tr>
<td align="right" >
UserName:
</td>
<td>
<asp:TextBox ID="txtuser" runat="server"/>
</td>
</tr>
<tr>
<td align="right" >
Password:
</td>
<td>
<asp:TextBox ID="txtpwd" runat="server"/>
</td>
</tr>
<tr>
<td align="right">
FirstName:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"/>
</td>
</tr>
<tr>
<td align="right">
LastName:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"/>
</td>
</tr>
<tr>
<td align="right">
Email:
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"/>
</td>
</tr>
<tr>
<td align="right" >
Phone No:
</td>
<td>
<asp:TextBox ID="txtphone" runat="server"/>
</td>
</tr>
<tr>
<td align="right" >
Location:
</td>
<td align="left">
<asp:TextBox ID="txtlocation" runat="server"/>
</td>
</tr>
<tr>
<td></td>
<td align="left" >
<asp:Button ID="btnsubmit" runat="server" Text="Save"/>
<input type="reset" value="Reset" />
</td>
</tr>
</table>
</asp:Panel>
<ajax:CollapsiblePanelExtender
ID="CollapsiblePanelExtender1"
runat="server"
CollapseControlID="pnlClick"
Collapsed="true"
ExpandControlID="pnlClick"
TextLabelID="lblMessage"
CollapsedText="Show"
ExpandedText="Hide"
ImageControlID="imgArrows"
CollapsedImage="downarrow.jpg"
ExpandedImage="uparrow.jpg"
ExpandDirection="Vertical"
TargetControlID="pnlCollapsable"
ScrollContents="false ">
</ajax:CollapsiblePanelExtender>
</div>
</form>
</body>
</html>

How to Use Accordian panel control


<style type="text/css">
.accordionContent {
background-color: #D3DEEF;
border-color: -moz-use-text-color #2F4F4F #2F4F4F;
border-right: 1px dashed #2F4F4F;
border-style: none dashed dashed;
border-width: medium 1px 1px;
padding: 10px 5px 5px;
width:20%;
}
.accordionHeaderSelected {
background-color: #5078B3;
border: 1px solid #2F4F4F;
color: white;
cursor: pointer;
font-family: Arial,Sans-Serif;
font-size: 12px;
font-weight: bold;
margin-top: 5px;
padding: 5px;
width:20%;
}
.accordionHeader {
background-color: #2E4D7B;
border: 1px solid #2F4F4F;
color: white;
cursor: pointer;
font-family: Arial,Sans-Serif;
font-size: 12px;
font-weight: bold;
margin-top: 5px;
padding: 5px;
width:20%;
}
.href
{
color:White;
font-weight:bold;
text-decoration:none;
}
</style>





<ajax:Accordion ID="UserAccordion" runat="server" SelectedIndex="0" HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent" FadeTransitions="true" SuppressHeaderPostbacks="true" TransitionDuration="250" FramesPerSecond="40" RequireOpenedPane="false" AutoSize="None" >
<Panes>
<ajax:AccordionPane ID="AccordionPane1" runat="server">
<Header><a href="#" class="href">New User</a></Header>
<Content>
<asp:Panel ID="UserReg" runat="server">
<table align="center">
<tr>
<td></td>
<td align="right" >
</td>
<td align="center">
<b>Registration Form</b>
</td>
</tr>
<tr>
<td></td>
<td align="right" >
UserName:
</td>
<td>
<asp:TextBox ID="txtuser" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td align="right" >
Password:
</td>
<td>
<asp:TextBox ID="txtpwd" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td align="right">
FirstName:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td align="right">
LastName:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td align="right">
Email:
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td align="right" >
Phone No:
</td>
<td>
<asp:TextBox ID="txtphone" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td align="right" >
Location:
</td>
<td align="left">
<asp:TextBox ID="txtlocation" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td align="left" ><asp:Button ID="btnsubmit" runat="server" Text="Save"/>
<input type="reset" value="Reset" />
</td>
</tr>
</table>
</asp:Panel>
</Content>
</ajax:AccordionPane>
<ajax:AccordionPane ID="AccordionPane2" runat="server">
<Header><a href="#" class="href">User Detail</a></Header>
<Content>
<asp:Panel ID="Panel1" runat="server">
<table align="center">
<tr>
<td align="right" colspan="2">
UserName:
</td>
<td>
<b>Suresh Dasari</b>
</td>
</tr>
<tr>
<td align="right" colspan="2">
FirstName:
</td>
<td>
<b>Suresh</b>
</td>
</tr>
<tr>
<td align="right" colspan="2">
LastName:
</td>
<td>
<b>Dasari</b>
</td>
</tr>
<tr>
<td align="right" colspan="2">
Email:
</td>
<td>
<b>sureshbabudasari@gmail.com</b>
</td>
</tr>
<tr>
<td align="right" colspan="2" >
Phone No:
</td>
<td>
<b>1234567890</b>
</td>
</tr>
<tr>
<td align="right" colspan="2" >
Location:
</td>
<td align="left">
<b>Hyderabad</b>
</td>
</tr>
</table>
</asp:Panel>
</Content>
</ajax:AccordionPane>
<ajax:AccordionPane ID="AccordionPane3" runat="server">
<Header><a href="#" class="href">Job Details</a> </Header>
<Content>
<asp:Panel ID="Panel2" runat="server">
<table align="center">
<tr>
<td></td>
<td align="right">
Job Type:
</td>
<td>
<b>Software</b>
</td>
</tr>
<tr>
<td></td>
<td align="right">
Industry:
</td>
<td>
<b>IT</b>
</td>
</tr>
<tr>
<td></td>
<td align="right">
Designation:
</td>
<td>
<b>Software Engineer</b>
</td>
</tr>
<tr>
<td></td>
<td align="right">
Company:
</td>
<td>
<b>aspdotnet-suresh</b>
</td>
</tr>
<tr>
<td></td>
<td align="right" >
Phone No:
</td>
<td>
<b>1234567890</b>
</td>
</tr>
<tr>
<td></td>
<td align="right" >
Location:
</td>
<td align="left">
<b>Hyderabad</b>
</td>
</tr>
</table>
</asp:Panel>
</Content>
</ajax:AccordionPane>
</Panes>
</ajax:Accordion>

Sunday, 15 April 2012

How to Use Form Authentications Applications


these code we have to write in web.config file.......

<authentication mode="Forms">
<forms name="f1" loginUrl="login.aspx">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>

How to use Appsettings values into our application


write code in web.config..........

<appSettings>
<add key="add" value="S R Nagar AmeerPet Hyderabad"/>
<add key="const" value="user id=sa;password=123;database=mydatabase;data source=."/>
</appSettings>





 protected void Page_Load(object sender, EventArgs e)
    {
        System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection();
        Label2.Text=ConfigurationSettings.AppSettings["add"];
        cn.ConnectionString=ConfigurationSettings.AppSettings["const"];
    }

How to Put the data in session


protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection("user id=sa;password=123;database=mydatabase;data source=.");
        SqlDataAdapter da = new SqlDataAdapter("select * from employee", cn);
        DataSet ds = new DataSet();
        da.Fill(ds,"emp");
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        Session["mydata"]=ds;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("getSessionDb.aspx");
    }







 protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds=(DataSet)Session["mydata"];
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        DetailsView1.DataSource = ds.Tables[0];
        DetailsView1.DataBind();
    }
}

How to Store Username and Passwords in cookies


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            HttpCookie obj1, obj2;
            obj1=Request.Cookies["uname"];
            obj2 = Request.Cookies["pwd"];
            if (obj1 != null && obj2 != null)
            {
                Response.Write(obj1.Value);
                if (obj1.Value == "username" && obj2.Value == "password")
                {
                    Server.Transfer("welcome.aspx");
                }
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (t1.Text == "username" && t2.Text == "password")
        {
            if (c1.Checked)
            {
                HttpCookie e1, e2;
                e1 = new HttpCookie("uname");
                e2 = new HttpCookie("pwd");
                e1.Value = t1.Text;
                e2.Value = t2.Text;
               
                e1.Expires = DateTime.Now.AddMinutes(2);
                e2.Expires = DateTime.Now.AddMinutes(2);
                Response.AppendCookie(e1);
                Response.AppendCookie(e2);
            }
            Server.Transfer("welcome.aspx");
        }// login parameter verification
        else
        {
            Response.Write("Invalied Login");
        }
    }
}

Friday, 13 April 2012

How to image crop to large size to smaller size with out spoiling the image quality


write class file............
........................................

using System;
using System.Collections.Generic;

using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;


/// <summary>
/// Summary description for PhotoUploader
/// </summary>
    public class PhotoUploader
    {
        FileUpload photo;
        string _imageName;
        string _path;
        string _outputMessage;
        int _newWidth;

        //GET AND SET IMAGE NAME
        public string ImageName
        {
            get { return _imageName; }
            set { _imageName = value; }
        }

        //GET AND SET IMAGE PATH
        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }

        //GET AND SET NEW WIDTH
        public int NewWidth
        {
            get { return _newWidth; }
            set { _newWidth = value; }
        }

        //GET AND SET ERROR MESSAGE
        public string OutputMessage
        {
            get { return _outputMessage; }
            set { _outputMessage = value; }
        }

        public bool StartUploadProcess(FileUpload ProductPhoto, int LargestWidthPX, string MapPath)
        {
            photo = ProductPhoto;
            ImageName = photo.FileName.Replace(" ", "").Replace("%20", "");

            //--- make sure image is in acceptable type
            //if (ImageName.ToLower().EndsWith(".jpg") || ImageName.ToLower().EndsWith(".jpeg") || ImageName.ToLower().EndsWith(".png") || ImageName.ToLower().EndsWith(".gif"))
            //{
            //    if ((ImageName != null))
            //    {
                    if (UploadPhoto(LargestWidthPX, MapPath))
                    {
                        //OutputMessage = "Photo was successfully uploaded.";
                        return true;
                    }
                //}
                //else
                //{
                //    OutputMessage = "No photo supplied. Please selecte a photo.";
                //    return false;
                //}
            //}
            //else
            //{
            //    OutputMessage = "The photo is not a supported type. Photo must be .jpg, .png or .gif";
            //    return false;
            //}
            return false;
        }

        protected bool UploadPhoto(int LargestWidthPX, string MapPath)
        {
            Path = MapPath;
            photo.SaveAs(HttpContext.Current.Server.MapPath(Path + ImageName.Replace(" ", "").Replace("%20", "")));
            NewWidth = LargestWidthPX;

            if (resizeImage())
            {
                NewWidth = 257;
                //if (resizeImage())
                //{
                //    NewWidth = 100;
                //    if (resizeImage())
                //    {
                //        File.Delete(HttpContext.Current.Server.MapPath(Path + photo.FileName.Replace(" ", "").Replace("%20", "")));
                //        return true;
                //    }
                //}
                File.Delete(HttpContext.Current.Server.MapPath(Path + photo.FileName.Replace(" ", "").Replace("%20", "")));
                  return true;
            }
            return false;
        }
        protected bool resizeImage()
        {
            string originalFileName = null;
            string newFileName = null;
            Bitmap tmpImage = default(Bitmap);
            Bitmap newImage = default(Bitmap);
            Graphics g = default(Graphics);
            int newHeight = 0;
            FileStream fs = default(FileStream);
            originalFileName = HttpContext.Current.Server.MapPath(Path + ImageName.Replace(" ", "").Replace("%20", ""));
            if (File.Exists(originalFileName))
            {
                try
                {
                    fs = new FileStream(originalFileName, FileMode.Open);
                    tmpImage = (Bitmap)Bitmap.FromStream(fs);
                    fs.Close();

                    //newHeight = (NewWidth * tmpImage.Height) / tmpImage.Width;
                   // newImage = new Bitmap(NewWidth, newHeight);

                    newHeight = 224;
                    newImage = new Bitmap(257, 224);

                    g = Graphics.FromImage(newImage);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                     g.DrawImage(tmpImage, 0, 0, NewWidth, newHeight);
                    g.DrawImage(tmpImage, 0, 0, 257, 224);
                    g.Dispose();

                    newFileName = NewWidth.ToString() + "_" + ImageName.Replace(" ", "").Replace("%20", "");
                    newImage.Save(HttpContext.Current.Server.MapPath(Path + newFileName), System.Drawing.Imaging.ImageFormat.Jpeg);
                    newImage.Dispose();
                    tmpImage.Dispose();

                    tmpImage = null;
                    newImage = null;
                    g = null;
                    return true;
                }
                catch (Exception ex)
                {
                    OutputMessage = "There was an error processing the request and we have been notified. Please try again later.";
                    tmpImage = null;
                    newImage = null;
                    g = null;
                    return false;
                }
            }
            else
            {
                OutputMessage = "There was an error processing the request and we have been notified. Please try again later.";
                tmpImage = null;
                newImage = null;
                g = null;
                return false;
            }
        }

    }






in C# code


 if (uploader.StartUploadProcess(FileUpload1, 600, "~/CroppedImages/"))
                {
                    x = FileUpload1.PostedFile.FileName;

                }


it will crop and save into that folder


display 7 days before records from the data base


select title, createdDate, lastdate  from date_testing
where (month(createdDate)=month(getdate()))
and (month(createdDate) between month(getdate())-1 and month(getdate())+1     )
and (day(createdDate) between day(getdate())-7 and day(getdate())+3     )


use this query ..................

Thursday, 12 April 2012

Display PDF File in Web page Using Iframe in ASP.NET


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <iframe height="400" width="400" id="pdfFrame" runat="server"></iframe>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </div>
    </form>
</body>
</html>
        


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class pdfview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        pdfFrame.Attributes.Add("src", "PDFs/tutorial.pdf");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       
    }
}


ur system must have adobe reader

.....................................sriraj.....................................