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) + " ";

Tuesday, May 29, 2012

How to connect Database and other events in User control



 
   Before started this topic I have already  given a topic on  User Control  for a fundamental idea. Here a question arises if we will take ASP.NET controls then how to connect database and other events of those controls. We know that user control page is same as ASPX page so coding is also same.

 Step: 1

 Create a user table in our database



 Step: 2
 
   Right click on the folder(User Control) in the web site and add new item as 'WebUserControl.ascx'  and  rename as 'Search.ascx'.

  Add the following code in design page

Source Code :-


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


<table class="style1">
    <tr>
        <td style="text-align: right" width="40%">
            <asp:Label ID="Label1" runat="server" Text="Search"></asp:Label>
        </td>
        <td><asp:DropDownList ID="DDLUser" runat="server"
    onselectedindexchanged="DDLUser_SelectedIndexChanged" AutoPostBack="True">
    </asp:DropDownList>

            &nbsp;</td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td width="60%"><asp:GridView ID="GridView1" runat="server">
</asp:GridView>
            &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.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class UserControl_LedgerDB : System.Web.UI.UserControl
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {

        con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
        DDLedger.Height = m_ImageHeight;

        if(IsPostBack==false )
        {
         
            da = new SqlDataAdapter("select username,userid from users",con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
             DDLUser .DataSource = dt;
             DDLUser .DataTextField = "username";
             DDLUser .DataValueField = "userid";
             DDLUser .DataBind();
        }
    }


    protected void DDLUser_SelectedIndexChanged(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("select * from users where ledgerid='"+  DDLUser .SelectedValue +"'", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataTable dt = ds.Tables[0];
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
 
}


Step:3


   After creating this user control right click on the folder(My Project) and add new item as 'Default.aspx'   and  rename as 'MyPage2.aspx'. Then register the user control page in this page as

 <%@ Register TagPrefix="User" TagName="Username" Src="~/UserControl/ Search.ascx" %>
   

   then  add   this  control anywhere in the page as

       < User : Username  ID="username" runat="server" Visible="True"  />

Step:4


Run the page and on selected index change of user we can able to see the details.









Monday, May 28, 2012

Working with user control in asp.net



       A user control is a file we create that contains a set of other ASP.NET controls and code grouped
together to provide common functionality. The user control can then be used on different pages
within a website. Ex: In our website there is more than one registration pages for different purpose but the addresses  like  country, state,city,plot number, street and pin code etc are common in each registration page so at that time it is required.

  Here I am taking a message box which will display whenever I required

 Step: 1

   After create a new website  right click on the website and add a new folder as 'User Control'.This folder will contain all user control if more than one required.
 
   Right click on the folder and add new item as 'WebUserControl.ascx'  and  rename as 'Popup.ascx'. Here I have taken AJAX and some image file of my choice.

  Add the following code in design page

  Source Code :-

   <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PopUp.ascx.cs" Inherits="Website.App_WebControls.App_UserControls.PopUp" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
 <asp:Button runat="server" ID="BtnMessage" Style="display: none" />
    <asp:ModalPopupExtender ID="modalMessage" runat="server" TargetControlID="BtnMessage"
        PopupControlID="PnlMessage" OkControlID="Okbtn" CancelControlID="imgClose" BackgroundCssClass="ModalBackgroundCSS">
    </asp:ModalPopupExtender>
    <asp:Panel runat="Server" ID="PnlMessage" DefaultButton="Okbtn" Style="border: solid 2px #BBBBBB;
        font-family: Arial; width: 325px; height: 150px">
        <table style="width: 100%; border: 0px none;border-collapse:collapse; " cellspacing="-1" cellpadding="-1" >
            <tr style="background-color:Teal; height: 30px; color: White; font-size: 15px;">
                <td colspan="2">
                    <table style="width: 100%;">
                        <tr>
                            <td style="width: 95%">
                                Message from My Project
                            </td>
                            <td>
                                <asp:Image ID="imgClose" runat="server" ImageUrl="../../images/quite.png" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr style="background-color: White; height: 90px">
                <td align="right">
                    <asp:Image ID="imgError" runat="server" ImageUrl="~/images/error.jpg" />
                </td>
                <td>
                    <div style="margin-left: 2%; width: 90%; font-size: 13px;">
                        <asp:Label ID="LblModalMessage" runat="server" Text=""></asp:Label></div>
                </td>
            </tr>
            <tr style="height: 30px; background-color: Teal">
                <td colspan="2" align="right">
                    <asp:Button ID="Okbtn" runat="server" Text="OK" Width="90px" Font-Size="13px" CausesValidation="false" />
                </td>
            </tr>
        </table>
    </asp:Panel>

Design View :-



N.B : No need of writing code in PopUp.ascx.cs page

Step: 2


   After creating this user control  right click on the website and add a new folder as 'My Project'.This    folder will contain all aspx pages if more than one required.
 
   Right click on the folder and add new item as 'Default.aspx'   and  rename as 'MyPage1.aspx'. Then register the user control page in this page as

   <%@ Register Src="~/UserControl/PopUp.ascx"  TagName="Pop" TagPrefix="popup" %>
   

   then  add   this  control anywhere in the page as

    <popup:Pop ID="MessagePop" runat="server" Visible="false" /> 


 Step: 3

  After finished the design create a user defined method as

 void Message(string msg)
        {
            ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            UserControl uc = (UserControl)cp.FindControl("MessagePop");
            if (uc != null)
            {
                Label lb = (Label)uc.FindControl("LblModalMessage");
                lb.Text = msg;
                MessagePop.Visible = true;
                AjaxControlToolkit.ModalPopupExtender modal = (AjaxControlToolkit.ModalPopupExtender)uc.FindControl("modalMessage");
                modal.Show();
            }
        }


    In button click event  or  whenever the message required  just call

    Message("Data Insereted Successfully !");