Saturday, July 14, 2012

Accordian Pane Example in ASP.Net


     If our page contains many controls and the page does not look good. That time we have to take the AJAX  Accordion Pane  and our all controls should group wise.
 
     Before use of AJAX we must have "AjaxControlToolkit.dll"  and it should attached to our project. We can download the  "AjaxControlToolkit.dll" . 


  Steps: 1 to Add the  "AjaxControlToolkit.dll" . 
   
     Rirgt click on any Tab of  of ToolBox -> Add new Tab -> Rename the tab to 'Ajax Client-Tool Kit ' ->
Again Right click on this tab -> Choose Items -> Browse the location where the "AjaxControlToolkit.dll" has saved -> Ok


  Steps: 2
  

    Design the page like this 

   NB: After adding the Accordian Pane to our page the proporties and events of controls  should write by us in ASPX page. Double click on control  can not create event in ASPX page


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


<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>
   <style type="text/css">
        .accordionContent
        {
            background-color: #CCFF66;
            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: 60%;
        }
        .accordionHeaderSelected
        {
            background-color: Orange;
            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: 60%;
        }
        .accordionHeader
        {
            background-color:#669900;
            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: 60%;
        }
        .href
        {
            color: White;
            font-weight: bold;
            text-decoration: none;
        }
        #Body1
        {
            font-weight: 700;
        }
    </style>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Accordion ID="Accordion1" runat="server" SelectedIndex="0" SuppressHeaderPostbacks="false"
                AutoSize="None" RequireOpenedPane="false" FadeTransitions="true" TransitionDuration="250" HeaderCssClass="accordionHeader" 
                ContentCssClass="accordionContent"  FramesPerSecond="40">
                <Panes>
                    <asp:AccordionPane ID="Acc1" runat="server">
                        <Header>
                            Personal Information
                        </Header>
                        <Content>
                            <table class="style1">
                               
                                <tr>
                                    <td>
                                        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td>
                                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td width="40%">
                                        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td width="60%">
                                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td>
                                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td>
                                        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                            </table>
                        </Content>
                    </asp:AccordionPane>
                    <asp:AccordionPane ID="AccordionPane1" runat="server">
                     <Header>
                            Address Details
                        </Header>
                        <Content>
                            <table class="style1">
                               
                                <tr>
                                    <td>
                                        <asp:Label ID="Label5" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td>
                                        <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td width="40%">
                                        <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td width="60%">
                                        <asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Label7" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td>
                                        <asp:TextBox ID="TextBox9" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Label8" runat="server" Text="Label"></asp:Label>
                                        &nbsp;
                                    </td>
                                    <td>
                                        <asp:TextBox ID="TextBox10" runat="server"></asp:TextBox>
                                        &nbsp;
                                    </td>
                                </tr>
                            </table>
                        </Content>
                    </asp:AccordionPane>
                </Panes>
            </asp:Accordion>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>



   

Monday, July 9, 2012

How to work File Upload Control inside Update panel in AJAX and Accordian Pane with Master Page


    Generally we use master page in our project and as it is a template we take common controls inside it. if we are using AJAX then we take update panel in master page. Or we can take update panel in our page individually. Now the problem is some controls are not work. Ex: FileUpload control doesnot work .

                if (FileUpDigitalSignature.HasFile)
                {
                    newCompInfo.UpDigitalSignature = Path.GetFileName(FileUpDigitalSignature.FileName);
                    FileUpArticle.SaveAs(Server.MapPath("~/images/") + newCompInfo.UpDigitalSignature);
                    StatusLabel.Text = "Upload status: File uploaded!";                
                }

 so here we have to control the flow through  a Trigger

          #region Method to Add Trigger to UpdatePanel
        public void AddTrigger()
        {
            UpdatePanelControlTrigger trigger = new PostBackTrigger();
            trigger.ControlID =  BtnAttachedSave .UniqueID;
            UpdatePanel panel = (UpdatePanel)this.Page.Master.FindControl("UpdatePanel1");
            panel.Triggers.Add(trigger);
        }
        #endregion

Now call this method in the page load event

       protected void Page_Load(object sender, EventArgs e)
        {

             AddTrigger();
       //or
              ScriptManager.GetCurrent(this).RegisterPostBackControl(BtnAttachedSave);
            if (IsPostBack == false)
            {
             
            }

        }


After using this trigger the file upload control will work.


Friday, July 6, 2012

Solution of DateTime problem in ASP.Net



   In our project we insert date to our database table through Textbox or through AJAX calender extender of through calender control. But the default format of  table is "MM/dd/yyyy". It gives error  when we send date in a incorrect format . So I am explaining the way which will not fail ever

               string[] date = TxtDate.Text.Split(new char[] { '/' });
               string NewDate = date[1] + "/" + date[0] + "/" + date[2];
         
               Insert into Table (JoinDate) values ('"+NewDate+"' );

Wednesday, June 27, 2012

Gridview User Control data manipulation In ASPX page


  Sometimes we create user control to reuse in our project in different pages means to access the common functionality.Now the difficult thing is to manipulate the data of that user control in our ASPX page.

  here is a simple demo on this topic



  Step-1

   create a table according to your requirement.here the Fms_Demo table is below

     Fms_Damo

     Roll   int  (PK,Identity)
     Age   int
     Name   varchar(50)

 Step-2

   Right click on Project -> Add NewItem -> Web User Control -> Rename the control as 'EventInASPXpage.ascx' and press Ok

Design View :

   <%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventInASPXpage.ascx.cs" Inherits="UserControl_EventInASPXpage" %>
<style type="text/css">
    .style1
    {
        width: 100%;
    }
</style>

<table class="style1">
    <tr>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
     
        <td colspan="2">
            <asp:GridView ID="GvUser"  runat="server" onrowcommand="GvUser_RowCommand"
                AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField HeaderText="Link">
                        <ItemTemplate>
                            <asp:LinkButton ID="LnkUser" CommandArgument='<%#Eval("Roll") %>' runat="server">LinkButton</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="name" HeaderText="Name" />
                    <asp:BoundField DataField="Roll" HeaderText="Roll" />
                </Columns>
            </asp:GridView>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="BtnUserButton" runat="server"
                Text="UserControl Save Button" onclick="BtnUserButton_Click" />
        </td>
        <td>
            &nbsp;</td>
    </tr>
</table>

  C# Code

  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 UserControl_EventInASPXpage : System.Web.UI.UserControl
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;
    SqlDataAdapter da;
    DataSet ds;

// Here we have declare event handler to fire event in ASPX page for the respective control. EventHandler is  used for whole control and CommandEventHandler is used for part of a control.


    public event EventHandler buttonClick;
    public event CommandEventHandler linkButtonClick;
 
 

    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
        con.Open();
        cmd = new SqlCommand("select * from fms_demo", con);
        dr = cmd.ExecuteReader();
        GvUser.DataSource = dr;
        GvUser.DataBind();
        con.Close();
    }
 
    protected void BtnUserButton_Click(object sender, EventArgs e)
    {
      buttonClick(Events, e);
    }
    protected void GvUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        linkButtonClick(Events, e);
    }
 
}

Step-3


  Right click on Project -> Add NewItem -> Web Form -> Rename the form as 'FrmUserControlEvent.aspx' and press Ok

   Design View

  <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FrmUserControlEvent.aspx.cs" Inherits="FrmUserControlEvent" %>
  <%@ Register Src="~/UserControl/EventInASPXpage.ascx" TagPrefix="UserEvent" TagName="UserControl" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">  
 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server"  >
        <ContentTemplate>
            <userevent:usercontrol ID="UserControlButton1"  runat="server" Visible="true"  />

    <asp:Panel ID="Panel1" runat="server">
     <table class="style1">
        <tr>
            <td class="style2">
                </td>
            <td class="style2">
                <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
            </td>
        </tr>
        <tr>
            <td style="text-align: right" width="40%">
                <asp:Label ID="Label1" runat="server" Text="Roll"></asp:Label>
            </td>
            <td width="60%">
                <asp:TextBox ID="TxtRoll" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td style="text-align: right" width="40%">
                <asp:Label ID="Label2" runat="server" Text="Age"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TxtAge" runat= "server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td style="text-align: right">
                <asp:Label ID="Label3" runat="server" Text="Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
            </td>
        </tr>
    </table>

    </asp:Panel>
        </ContentTemplate>    
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="UserControlButton1" />
    </Triggers>
    </asp:UpdatePanel>
   
</asp:Content>

<asp:Content ID="Content3" runat="server" contentplaceholderid="HeadContent">
    <style type="text/css">
        .style2
        {
            height: 21px;
        }
    </style>
</asp:Content>

  C# Code


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 FrmUserControlEvent : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;
 

    protected void Page_Load(object sender, EventArgs e)
    {
       con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);

      UserControlButton1.buttonClick +=new EventHandler(UserControlButton1_buttonClick);
      UserControlButton1.linkButtonClick +=new CommandEventHandler(UserControlButton1_linkButtonClick);
   
    }
    protected void UserControlButton1_linkButtonClick(object sender, CommandEventArgs e)
    {
     
 
        con.Open();
        cmd = new SqlCommand("select name,age from fms_demo where roll='"+ e.CommandArgument.ToString() +"'",con);
        dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            TxtRoll.Text=e.CommandArgument.ToString();
            TxtName.Text = dr[0].ToString();
            TxtAge.Text = dr[1].ToString();
        }
        con.Close();
     
     

    }
    protected void UserControlButton1_buttonClick(object sender, EventArgs e)
    {
        try
        {

            con.Open();
            string ins="update fms_demo set name='"+ TxtName.Text +"',age='"+ TxtAge.Text +"' where roll='"+ TxtRoll.Text +"'";
            cmd = new SqlCommand(ins,con);
            cmd.ExecuteNonQuery();
            con.Close();
            Label4.Text = "Successfully Updated.................";
// To reload the page
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "Script", "window.location.reload()", true);
         
        }
        catch (Exception ex)
        {
            Label4.Text = ex.Message.ToString();
        }

    }   
 
}







     

Monday, June 18, 2012

ADO .Net Batch Sql Statements with Data Reader,Data Adapter & Stored Procedure


   Batch Sql statements are use full for retrieving data from database. ADO .Net supports batch sql statements. It requires less memory and faster because we don't need to take more Command object or DataAdapter object to read data.


NB: Please design your own tables and stored procedures.

Design View :-



<%@ 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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:gridview ID="Gridview1" runat="server"></asp:gridview>
    <asp:gridview ID="Gridview2" runat="server"></asp:gridview>
        <asp:Button ID="BtnReader" runat="server" Text="Data Reader"
            onclick="BtnReader_Click" />
        <asp:Button ID="BtnAdapter"
            runat="server" Text="Data Adapter" onclick="BtnAdapter_Click" />
        <asp:Button ID="BtnStored" runat="server" Text="Stored Procedure"
            onclick="BtnStored_Click" />
    </div>
    </form>
</body>
</html>


C# Code :-

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 Default3 : System.Web.UI.Page
{
    SqlConnection con;
    SqlDataAdapter da;
    SqlCommand cmd;
    DataSet ds;
    SqlDataReader dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["Satya"].ConnectionString);
        con.Open();
        if (!IsPostBack)
        {
          
        }
    }
    public void satya_DA()
    {
        da = new SqlDataAdapter("Select * from Rakesh;Select * from Demo", con);
        ds = new DataSet();
        da.Fill(ds);

        Gridview1.DataSource = ds.Tables[0].DefaultView;
        Gridview1.DataBind();
        Gridview2.DataSource = ds.Tables[1].DefaultView;
        Gridview2.DataBind();

    }
    public void satya_Reader()
    {
        using (cmd = new SqlCommand("Select * from Rakesh;Select * from Demo", con))
        {
            using (dr = cmd.ExecuteReader())
            {
                Gridview1.DataSource = dr;
                Gridview1.DataBind();
                dr.NextResult();
                Gridview2.DataSource = dr;
                Gridview2.DataBind();
            }

        }

    }
    public void satya_SP()
    {      
        cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "exec Select_Employee_Sallary_Qualification exec Select_Employee_Sallary_Qualification1";
        da = new SqlDataAdapter(cmd);
        ds = new DataSet();
        da.Fill(ds);
        Gridview1.DataSource = ds.Tables[0].DefaultView;
        Gridview1.DataBind();
        Gridview2.DataSource = ds.Tables[1].DefaultView;
        Gridview2.DataBind();
        da.Dispose();
        con.Close();

    }
    protected void BtnReader_Click(object sender, EventArgs e)
    {
        satya_Reader();
    }
    protected void BtnAdapter_Click(object sender, EventArgs e)
    {
        satya_DA();
    }
    protected void BtnStored_Click(object sender, EventArgs e)
    {
        satya_SP();
    }
}


Monday, June 11, 2012

How to load Login page for Authenticate user



    Step:-1

    Design a Master page as required to our need and just add  this code  in the MasterPage.cs

  string userId;
    protected void Page_Load(object sender, EventArgs e)
    {
        //long userId = Convert.ToInt64(Session["UserId"]);
        if (Session["UserId"] != null)
        {
            userId = Session["UserId"].ToString();
        }

        if (!IsPostBack)
        {

            if (userId == "" || userId == null)
            {

                Response.Redirect("~/FrmLoginWithoutBackToHistory.aspx", false);

            }

        }
    }
    protected void Page_Init(object sender, EventArgs e)
    {

        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.Cache.SetNoStore();
       

    }

    protected void lnkLogout_Click1(object sender, EventArgs e)
    {
        Session.Clear();
        Session.Abandon();
        Response.Redirect("~/FrmLoginWithoutBackToHistory.aspx", false);
    }

 Step:-2

    Design a Login page as required to our need

     Design View 

     <form id="form1" runat="server">
    <div>
 
        <table class="style1" bgcolor="#999966">
            <tr>
                <td colspan="2" style="text-align: center">
                    <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Login Page"></asp:Label>
                </td>
           
            </tr>
            <tr>
                <td width="40%">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td style="text-align: right">
                    <asp:Label ID="Label2" runat="server" Text="User ID :"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="TxtUser" runat="server" Height="22px" Width="292px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    <asp:Label ID="Label3" runat="server" Text="Password :"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="TxtPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="BtnSubmit" runat="server" BackColor="#0066FF" Font-Bold="True"
                        onclick="BtnSubmit_Click" Text="Log In" />
                </td>
            </tr>
        </table>
 
    </div>
    </form>


   C# Code:


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

public partial class FrmLoginWithoutBackToHistory : System.Web.UI.Page
{
    string user = "satya";
    string pass = "1234";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
//  we can code here for Database table
        if (TxtUser.Text.Trim() == user && TxtPassword.Text.Trim() == pass)
        {
            Session["UserId"] = TxtUser.Text.Trim();
            Response.Redirect("Default.aspx", false);
        }
    }
}

 to clear  the session for more security in the web.config file

<system.web>
    <sessionState cookieless="true"></sessionState>
</system.web>




Monday, June 4, 2012

Break down a string in a regular interval



             Here i have given two ways .In which I am breaking down the string  when its index position is 10.


        string[] xx= new string[TextBox1.Text.Length];
        int l = xx.Length; int i;
        for (i = 0; i <= xx.Length - 1 && l>10; i += 10,l-=10)
        {
           st1 = TextBox1.Text.Substring(i,10 );
           st2 += st1+" ";
        }
        st1 = TextBox1.Text.Substring(i, l);
        st2 += st1 + " ";

===========================================

         int l = TextBox1.Text.Length; int i;
        for (i = 0; i <= TextBox1.Text.Length - 1 && l>10; i += 10,l-=10)
        {
           st2 += TextBox1.Text.Substring(i, 10) + " ";
        }
        st2 += TextBox1.Text.Substring(i, l) + " ";