Sunday, October 9, 2011

What is difference between OR (|) and Logical OR (||) ?

1. Logical OR Sign is || and AND Sign is  |.
2. Both work is same but Operation Method is Different 
for example 
if(a==10 || b==10) 
here if a =10 then condition is Satisfied and not going checking values of B. 
Moral One Operation for checking second i.e B values decrasesand in AND & operation 
if(a==10 | b==10)
here if a ==10 then also it is checking B value i.e  it is not necessary.    
    
Logical OR(||) is Best.    

What is difference between AND & and Logical AND &&?

1. Logical AND Sign is && and AND Sign is  &.
2. Both work is same but Operation Method is Different
for example
if(a==10 && b==10)
here if a =10 then only it going for  checking b value
if a !=10 then condition is not satisfied.
Moral One Operation for checking second values decrases
and in AND & operation
if(a==10 & b==10)
here if a !=10 then also it is checking B value it is not necessary.
Logical AND(&&) is Best.    

Wednesday, October 5, 2011

Custom Validation On ServerSide For Validate Number in asp.net

Server Side Custom Validation  For Number. 
it is check regular expression for Number and must be not  null value means 
Required Field Validation.
 
 CustomValidation.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomValidation.aspx.cs"
    Inherits="CustomValidation" %>

<!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>CustomValidation ASPdotNet-Example.blogspot.com</title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <h1>
        CustomValidation ASPdotNet-Example.blogspot.com</h1>
    <div>
        <table>
            <tr>
                <td>
                &nbsp;
                </td>
                <td>
  <asp:CustomValidator ID="CustomValidatorNumber" runat="server" ForeColor="Red" 
  ControlToValidate="txtValidation" ValidationGroup="Number"
  onservervalidate="CustomValidatorNumber_ServerValidate" 
                        ValidateEmptyText="True"></asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>
  <asp:Label ID="lblNumber" runat="server"  Text="Number"></asp:Label>
                </td>
                <td>
 <asp:TextBox ID="txtValidation" ValidationGroup="Number" runat="server">
</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                &nbsp;
                </td>
                <td>
  <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Number"
      onclick="btnSubmit_Click" />
                </td>
            </tr>
            <td>
                &nbsp;
                </td>
                <td>
         <asp:Label ID="lblMsg" runat="server" ForeColor="Green"></asp:Label>
                </td>
        </table>
    </div>
    </center>
    </form>
</body>
</html>
CustomValidation.aspx.cs

Sunday, October 2, 2011

gridview reorder row drag and drop

Drag and Drop GridView Row with jQuery.
Save Display Order in DataBase with WebMethod.
nodrag and nodrop for row that you are not want to drag and drop

gridview reorder row drag and drop




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

<!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">
    <script src="jquery-1.6.1.js" type="text/javascript"></script>
    <script src="jquery.tablednd_0_5.js" type="text/javascript"></script>
    <style>
        .noselect
        {
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
            user-select: none;
            cursor: move;
        }
        .tDnD_whileDrag
        {
            background-color: Lime;
        }
    </style>
    <title>ASPdotNET-Example.blogspot.com</title>

<script type="text/javascript">
var strorder;
$(document).ready(function() {
$('#GridViewReorder').tableDnD(
{
    onDrop: function(table, row) {
    reorder();
    $.ajax({
             type: "POST",
             url: "GridViewReOrderDragandDrop.aspx/GridViewReorders",
             data: '{"Reorder":"'+strorder+'"}',
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             cache: false,
             success: function (msg) {
             alert("Successfully Save ReOrder");
             }

           })
     }
}
);
});
function  reorder()
{ 
    strorder="";
    var totalid=$('#GridViewReorder tr td input').length;
    for(var i=0;i<totalid;i++)
    {
     strorder=strorder+$('#GridViewReorder tr td input')[i].getAttribute("value")+"|";
    }
}
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <center>
    <h1>GridView Reorder Drag And Drop</h1>
 <div>
 <asp:GridView ID="GridViewReorder" runat="server" HeaderStyle-CssClass="nodrag nodrop"
AutoGenerateColumns="False">
 <Columns>
    <asp:TemplateField ItemStyle-CssClass="noselect" HeaderText="ID">
      <ItemTemplate>
        <asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>
       <asp:HiddenField ID="hdnid" runat="server" Visible="true" Value='<%# Bind("id") %>' />
      </ItemTemplate>
     </asp:TemplateField>
        <asp:TemplateField ItemStyle-CssClass="noselect" HeaderText="Name">
       <ItemTemplate>
         <asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
         </ItemTemplate>
        </asp:TemplateField>
     <asp:TemplateField HeaderText="Display Order" ItemStyle-CssClass="noselect">
        <ItemTemplate>
          <asp:Label ID="lblOrder" runat="server" Text='<%# Bind("displayorder") %>'>
</asp:Label>
          </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</div>
    <h1> ASPdotNet-Example.blogspot.com</h1>
    </center>
    </form>
</body>
</html>
 


GridViewReOrderDragandDrop.aspx.cs

using System;
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;
using System.Web.Services;
public partial class GridViewReOrderDragandDrop : System.Web.UI.Page 
{
    SqlConnection strCon;
    string sql;
    SqlDataAdapter objAd;
    DataSet objDs;
    protected void Page_Load(object sender, EventArgs e)
    {
        GridViewReorder.DataSource = Con();
        GridViewReorder.DataBind();
    }
    protected DataSet Con()
    {
strCon = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
        objAd = new SqlDataAdapter("ListGrid", strCon);
        objDs = new DataSet();
        objAd.Fill(objDs);
        return objDs;
    }
    [WebMethod]

    public static void GridViewReorders(string Reorder)
    {
        string[] ListID = Reorder.Split('|');
        for (int i = 0; i < ListID.Length; i++)
        {
            if (ListID[i] != "" && ListID[i] !=null)
            {
                updateGridViewReorder(Convert.ToInt16(ListID[i]), i+1);
            }
        }

    }


    public static void updateGridViewReorder(int id, int DisplayOrder)
    {SqlConnection con ;
con= new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
        SqlCommand cmd = new SqlCommand("UpdateOrder");
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@id", id);
        cmd.Parameters.AddWithValue("@DisplayOrder",DisplayOrder);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    
    }
}

 Database Script

 

Thursday, September 29, 2011

how to start thread ?

using System;

using System.Threading;

public class ThreadTest {

    public void csharpeMethod() {

        int result = 1;

        Console.WriteLine(result.ToString() + "  Thread ID is  " +

                          AppDomain.GetCurrentThreadId().ToString());

    }

    public static void Main() {

        ThreadTest objThread = new ThreadTest ();

        objThread.csharpeMethod();

        ThreadStart objts = new ThreadStart(objThread.csharpeMethod);

        Thread obj = new Thread(objts);

        obj.Start();

    }

}


Sunday, September 25, 2011

Use Viewstate with UpdatePanel in asp.net

ViewState Can not use with UpdatePanel in ASP.NET Because When Page is not postBack at time viewstate is Available and If  Page is PostBack at time viewstate kill (Destroy). Now New ViewState is Generate that is used by On in Update Panel What is Solution fo viewstate? Solution is that make EnableViewState="true" in UpdatePanel. Put Hidden Filed in UpdatePanel and store Value in Hidden Field. Problem is Solve. Now If You want to use JavaScript Function Then you can Register That JavaScript Function in UpdatePanel Load Event
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
   // Add client-side script to call the JavaScript  function
   ScriptManager.RegisterStartupScript(this, this.GetType(),
                  Guid.NewGuid().ToString(),
                  "YourJAVASCRIPTfunctionName();", true);
}   

Sunday, July 17, 2011

calling asp.net method from jquery

ASP.NET Code Behind Method is Call by jQuery Function and AJAX.
Let's See How
jQuery.ASPX 
<%@ 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 runat="server">
<title>Untitled Page</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>

      <script type ="text/javascript">

          $(document).ready(function () {

              $('#<%=btnjQuery.ClientID %>').click(function () {

                  $.ajax({

                      type: "POST",

                      url: "jQuery.aspx/CodeBehindMethod",

                      data: "{}",

                      contentType: "application/json; charset=utf-8",

                     dataType: "json",

                     async: true,

                     cache: false,

                     success: function (msg) {

                         $('#result').text(msg.d); 

                     }

                 })

                 return false;

             });

         });

     </script>
    
    
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="btnjQuery" runat="server" Text="call jQuery Function" />

    <br /><br />

    <div id="result"></div>
    </div>
    </form>
</body>
</html>
well do not forget System.Web.Services NameSpace and
Method Must be Static and it's Variable also Static.
jQUery.aspx.cs 
 
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.Web.Services;

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

    }

    [WebMethod]

    public static string CodeBehindMethod()

       {

           return "Message from code behind Method.";

       }
}

Friday, July 15, 2011

Set default Culture in web.config file

<configuration>
<system.web>

<globalization

    culture="en-US"

    uiCulture="en-US/>
</system.web>

</configuration>

can i have more than one web.config file in one website?

yes, You have more than one web.config file. You can use it as your requirement.

what is Web.config ?

As name suggest web.config is web site configuration file.
Globally configure you website through web.config file.

Saturday, May 28, 2011

what is view in sql server ?

view is one type of virtual table so view does not contain physical memory.
view is just some columns and rows combination which is selected from one or
more table.just it contain query.
 view benefits :- 
view is provide abstract layer over database tables. it's provide security.
only some non sensitive columns select in query so confidential data can not
appear that particular user.
for example:-
create view view_name select name from tbladmin.    

Saturday, May 21, 2011

using SqlDataAdapter Update table

using System;

using System.Data;

using System.Data.SqlClient;



class UpdateusingdataobjAdapter
{
static void Main()
{
string cn="server=localhost;database=DBTEST;uid=sa;pwd=sa";
SqlConnection Connection = new SqlConnection(cn);
string query = @"select * from tblemp ";
string update = @"update tblemp set name = @name where id = @id";
try
{

   SqlDataobjAdapter objAd = new SqlDataobjAdapter();

   objAd.SelectCommand = new SqlCommand(query, Connection );
   DataSet objDs = new DataSet();  

   objAd.Fill(objDs, "tblemp");
   DataTable objDt = objDs.Tables["tblemp"];

   objDt.Rows[0]["name"] = "Ravi";

   foreach (DataRow row in objDt.Rows)
   {

    Console.WriteLine(

                  "{0} {1}",

                  row["name"].ToString(),

                  row["lastname"].ToString();

            }



     // Update tblemps

    SqlCommand objcmd = new SqlCommand(update, Connection );

    objcmd.Parameters.Add("@name",SqlDbType.NVarChar,15, "name");

    SqlParameter parm = objcmd.Parameters.objAdd("@id",SqlDbType.Int,4,"id");

    parm.SourceVersion = DataRowVersion.Original;

    objAd.UpdateCommand = objcmd;

    objAd.Update(objDs, "tblemp");

    }
catch(Exception e)
 {

            Console.WriteLine("Error: " + e);

 }
finally
 {

            Connection.Close();

 }

      } 

   }

Friday, May 20, 2011

Using Store Procedure customize Paging in GridView Data Control

On web 1000 of records are in Database.We need only small amount 
of data i.e 10,15 etc. default paging all records are load and
it take more time. Performance of our Application decreasing. 
we create custom Optimize Paging.
In this paging we retrieve only our page size data only from database 
for that we create store procedure.
Customize or Manual Paging Store procedure     
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  <Author,,ASPdotNet-Example.blogspot.com>
-- Create date: <Create Date,,May 20 2011>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[SP_Paging]
@PageIndex int,
@PageSize int,
@TotalRecord int output,
AS
BEGIN
 
 SET NOCOUNT ON;
select @TotalRecord=count(id) from tblemp
 
select * from 
(
select row_number() over (order by [id] asc )as RowNumber,
Name,depid,Salary from tblemp
)as a 
where a.rownumber between (@PageIndex-1)*@PageSize+1 AND 
(((@PageIndex-1)*@PageSize+1)+@PageSize)-1
END

Thursday, May 19, 2011

Way of Insert Data in Database Table with ADO.Net

There are many way Insert data in database table.
I described Five way here.
1. using sql command techniques insert data into database table 
2.Using Bind parameters sql command techniques insert data into database table 
3.using sql command with Parameters techniques insert data into database table 
4.Using ExecuteScalar and SqlCommand Insert data into Database Table 
5.using CommandBuilder insert datat in form datatable in datadase 
5 is Best and Optimize way of insert data into database table because in with 
using conncetionless (SqlDataAdpter) concepts and in insert in datatable form so 
it is best in Performance view and it can use with asp.net where large amount of
users are working.  

using CommandBuilder insert datat in form datatable in datadase

This is the best and optimize way of insert data in to database table 
with ado.net
InsertingDataUsingCommandBuilder
using System;
using System.Data;
using System.Data.SqlClient;

public class InsertingDataUsingCommandBuilder
{
 
static void Main(string[] args)
 {
string Cn="DataSource=(local);InitialCatalog=CaseManager;Integrated Security=true";
string Query="SELECT ID, Contact, Email FROM Test";
SqlConnection objConnection = new SqlConnection(Cn);
SqlDataAdapter objDataAdapter = new SqlDataAdapter(Query,objConnection);
SqlCommandBuilder objCmd = new SqlCommandBuilder(objDataAdapter);
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet);
DataRow objRow = objDataSet.Tables[0].NewRow();
objRow["ID"] = 520;
objRow["Contact"] = "Bill";
objRow["Email"] = "Ray";
objDataSet.Tables[0].Rows.Add(objRow);
objDataAdapter.Update(objDataSet);
        }
    }

Using ExecuteScalar and SqlCommand Insert data into Database Table

using System;

using System.Data;

using System.Data.SqlClient;
   

public class InsertingDataUsingSQLStatementsExecuteScalar

{

static void Main(string[] args)

{
string CN="Data Source=(local); Initial Catalog = DBNAME; Integrated Security=true; 
SqlConnection objConnection = new SqlConnection(CN);
            

String Query ="INSERT INTO tblTest(ID, Contact, Email) VALUES(3, 'Bill', 'John')";

SqlCommand objCmd = new SqlCommand(Query, onConnection);objConnection.Open();
objCmd.ExecuteScalar();
objConnection.Close();

} 
}


using sql command with Parameters techniques insert data into database table

 
 
 
using System;
using System.Data;
using System.Data.SqlClient;

class UsingParameterAndCommand
 {
    public static void Main() 
{
string cn="server=localhost;database=DBTEST;uid=sa;pwd=sa";
 SqlConnection Connection = new SqlConnection(cn);
        
        SqlCommand objCmd = Connection.CreateCommand();
        objCmd.CommandText =
          "INSERT INTO ASPTable (" +
          "  CustomerID, CompanyName, ContactName" +
          ") VALUES (" +
          "  @CustomerID, @CompanyName, @ContactName" +
          ")";
        objCmd.Parameters.Add("@CustomerID", "AB001");
        objCmd.Parameters.Add("@CompanyName", "MicroSoft");
        objCmd.Parameters.Add("@ContactName", "Bill");
        Connection.Open();
        objCmd.ExecuteNonQuery();
        Console.WriteLine("Successfully added row to ASPTable ");

        Connection.Close();
    }
}

Using Bind parameters sql command techniques insert data into database table

This techniques is better than
using sql command techniques insert data into database table 
because SqlDataAdapter is used here but not optimize solution. 
Bind Parameters techniques for Insert data
using System;
using System.Data;
using System.Data.SqlClient;

class bindParametersExample
{
      static void Main() 
{
string ConnectionString ="server=(local)\\SQLEXPRESS;database=DBTEST;
Integrated Security=SSPI";
string Query = @"select * from aspdotnetTable";
string InsertQuery = @"insert into aspdotnetTable(firstname,lastname)
values(@firstname,@lastname)";

         SqlConnection objConnection = new SqlConnection(ConnectionString );

         try{
            SqlDataAdapter objAd = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand(Query, objConnection );

            DataSet objDs = new DataSet();   
            objAd.Fill(objDs , "aspdotnetTable");

            DataTable objDataTable = objDs.Tables["aspdotnetTable"];

            DataRow objRow = objDataTable.NewRow();
            objRow["firstname"] = "Bill";
            objRow["lastname"] = "Gates";
            objDataTable.Rows.Add(objRow);

            foreach (DataRow row in objDataTable.Rows){
               Console.WriteLine(
                  "{0} {1}",
                  row["firstname"].ToString().PadRight(15),
                  row["lastname"].ToString().PadLeft(25));
            }

            // Insert data in to aspdotnetTable
       SqlCommand objCmd = new SqlCommand(InsertQuery, objConnection);
       objCmd.Parameters.Add("@firstname", SqlDbType.NVarChar, 10, "firstname");
       objCmd.Parameters.Add("@lastname",  SqlDbType.NVarChar, 20, "lastname");
       objAd.InsertCommand = objCmd;
       objAd.Update(objDs, "aspdotnetTable");
         } catch(Exception e) {
            Console.WriteLine("Error: " + e);
         } finally {
            objConnection.Close();
         }
      }  
   }

using sql command techniques insert data into database table

we must add using System.Data.SqlClient; namespace. 
now following code you can use.
This is Vary old Techniques. If we use techniques with Asp.net 
there is Pooling required because if there is large amount of users 
use this page than it is difficult to handle connnection.  
Insert into database using sqlcommand 
using System;
using System.Data;
using System.Data.SqlClient;

   class sqlcommandexample
{
      static void Main() 
      {
string CN="server=(local)\\SQLEXPRESS;database=DBTEST;Integrated Security=SSPI"; 
SqlConnection objCn = new SqlConnection(CN);
         SqlCommand objCmd= objCn.CreateCommand();

         try 
         {
objCn.Open();

objCmd.CommandText = "CREATE DATABASE NewDB";
Console.WriteLine(objCmd.CommandText);

objCmd.ExecuteNonQuery();
Console.WriteLine("Now is Database created and database");
objCn.ChangeDatabase("NewDB");

objCmd.CommandText = "CREATE TABLE aspdotnetTable(COL1 integer)";
Console.WriteLine(objCmd.CommandText);
Console.WriteLine("NO Rows Affected is: {0}", objCmd.ExecuteNonQuery());

objCmd.CommandText = "INSERT INTO aspdotnetTable VALUES (100)";
Console.WriteLine(objCmd.CommandText);
Console.WriteLine("NO Rows Affected is: {0}", objCmd.ExecuteNonQuery());
         
         } catch (SqlException ex) {
         
            Console.WriteLine(ex.ToString());
         
         } finally {  
         
            objCn.Close();
            Console.WriteLine("Connection Closed.");
         
         }
      }
   }

Monday, May 9, 2011

Customize Paging in DataList Data Control

 Custom Paging In Datalist Control
CustomPaging.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList ID="dtlEmp" runat="server">
            <HeaderTemplate>
                <table>
                    <tr>
                        <th>
                            ID
                        </th>
                        <th>
                            Name
                        </th>
                        <th>
                            DepID
                        </th>
                        <th>
                            Salary
                        </th>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
  <asp:Label ID="lblID" runat="server" 
Text='<%# Bind("id") %>'></asp:Label>
                    </td>
                    <td>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                    </td>
                    <td>
<asp:Label ID="lblDepID" runat="server" Text='<%# Bind("depid") %>'></asp:Label>
                    </td>
                    <td>
<asp:Label ID="lblSalary" runat="server" Text='<%# Bind("Salary") %>'></asp:Label>
                    </td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:DataList>
        <table>
            <tr>
                <td>
<a href="Default.aspx#BookMark" id="First" onserverclick="ShowFirstPage"
runat="server">
                        <img src="firstpage.gif" alt="" />
                    </a>
                </td>
                <td>
 <a href="Default.aspx#BookMark" id="Prev" onserverclick="ShowPrevPage"
runat="server">
                        <img src="prevpage.gif" alt="" />
                    </a>
                </td>
                <td>
<a href="Default.aspx#BookMark" id="Next" onserverclick="ShowNextPage"
runat="server">
                        <img src="nextpage.gif" alt="" />
                    </a>
                </td>
                <td>
<a href="Default.aspx#BookMark" id="Last" onserverclick="ShowLastPage"
runat="server">
                        <img src="lastpage.gif" alt="" />
                    </a>
                </td>
            </tr>
        </table>
        <asp:Label ID="lblCurrentIndex" runat="server" Text="0"></asp:Label>
        <asp:Label ID="lblPagesize" runat="server" Text="5"></asp:Label>
        <asp:Label ID="lblRecordCount" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

CustomPaging.aspx.cs
using System;
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 _Default : System.Web.UI.Page 
{
    SqlConnection objcn;
    DataSet objDs;
    SqlDataAdapter objAd;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindData();
    }
    public void BindData()
    {
        string Query="select * from tblEmp";
        objcn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"]
.ConnectionString);
            objAd = new SqlDataAdapter(Query, objcn);
            objDs = new DataSet();
        if (!IsPostBack)
        {
            objAd.Fill(objDs);
            lblRecordCount.Text=(objDs.Tables[0].Rows.Count).ToString();
            //objDs=null;
            //objDs=new DataSet();
       
        }
        objAd.Fill(objDs,Convert.ToInt32(lblCurrentIndex.Text),Convert.ToInt32
(lblPagesize.Text),"tblEmp");
        dtlEmp.DataSource = objDs.Tables["tblEmp"].DefaultView;
        dtlEmp.DataBind();

    }
    public void ShowFirstPage(object sender, EventArgs e)
    {
        lblCurrentIndex.Text = "0";
        BindData();
    }
    public void ShowPrevPage(object sender, EventArgs e)
    { 
        lblCurrentIndex.Text=((Convert.ToInt32(lblCurrentIndex.Text))-Convert.
ToInt32(lblPagesize.Text)).ToString();
        if(Convert.ToInt32(lblCurrentIndex.Text)<0)
        {
            lblCurrentIndex.Text="0";
        }
        BindData();
   
    }
    public void ShowNextPage(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCurrentIndex.Text) + 
Convert.ToInt32(lblPagesize.Text) < Convert.ToInt32(lblRecordCount.Text))
        {
            lblCurrentIndex.Text = (Convert.ToInt32(lblCurrentIndex.Text)
+ Convert.ToInt32(lblPagesize.Text)).ToString();

        }
        BindData();
    }
    public void ShowLastPage(object sender, EventArgs e)
    {
        int Mod = Convert.ToInt32(lblRecordCount.Text) /
Convert.ToInt32(lblPagesize.Text);
        if (Mod > 0)
        {
            lblCurrentIndex.Text = (Convert.ToInt32(lblRecordCount.Text) -
Mod).ToString();

        }
        else
        { 
        lblCurrentIndex.Text=(Convert.ToInt32(lblRecordCount.Text)-
Convert.ToInt32(lblPagesize.Text)).ToString();
        }
        BindData();
   
    }

}

Wednesday, April 27, 2011

Property in Tutorial in C sharp

Property is Smart Method.
below given property example.

Tuesday, April 26, 2011

Indexer in Csharp Example

The Indexer is also known as Smart Array.
Benefit with Indexer is that we not need to define Limit Value like Array.
Example Of Indexer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Indexer
{
class Tutorial
{
string [] name=new string[15];
public string this[int range]
{
set { name[range] = value; }
get { return name[range]; }
}
static void Main(string[] args)
{
Tutorial p = new Tutorial();
p[0] = "Mike";
p[1] = "Milan";
p[2] = "Vihar";
p[3] = "Vivek";
p[4] = "Sharad";
Console.Write(" {0} \n {1} \n {2} \n {3} \n {4}",p[0],p[1],p[2],p[3],p[4]);


Console.ReadLine();

}
}

Monday, April 25, 2011

Exception handling Divide By Zero Exception

DivideByZeroException Exception Handling
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exception handling 
{
    class Program
    {
        
        
        static void Main(string[] args)
        {
            int i;
            int j;
            int k;
            Console.WriteLine("Enter 1st No: ");
            i = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter 2nd No: ");
            j = int.Parse(Console.ReadLine());
            try
            {
                if (j == 0)
                {
                    throw new DivideByZeroException();
                }
                k = i / j;
                Console.WriteLine("Ans is " + k);
            }
            catch (DivideByZeroException)
            {
                    Console.WriteLine("Divide By Zero Not Possible..");
            
            }

            finally
            {
                Console.ReadLine();
            }
        }
    }
}
 

Sunday, April 24, 2011

GridView Data Control in ASP.net Example

For ASP.net Beginner
ToolBox in that Data in that GridView Pick up and Drag that Control to ASPX page.
Which is Look Like This Image

Saturday, April 23, 2011

Exception Handling IndexOutOfRangeException

Exception handling for index outof range exception in c sharp.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ass_45
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] name = new int[3];
            Console.WriteLine("Enter Array Value:");
            try
            {
                for (int i = 0; i <= 3; i++)
                {

                    name[i] = Convert.ToInt32(Console.ReadLine());

                }
                for (int i = 0; i <= 3; i++)
                {
                    Console.WriteLine("Array" + name[i]);
                }
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Array Out of Index Ha Ha Ha");
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }
}

Generics example in c sharp

Generics is belongs from System.Collections.Generic class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics
{
    public class Test
    {
        public T EmpID
        {
            set;
            get;
        }

        public void show(T t,N n)
        {
            if (typeof(T) == typeof(int) && typeof(N) == typeof(int))
            {
                int x = Convert.ToInt32(t);
                int y = Convert.ToInt32(n);
                Console.WriteLine(x + y);
            }
            else if (typeof(T) == typeof(string) && typeof(N) == typeof(int))
            {
                Console.WriteLine("The " + t + "'s Age is " + n);
            }

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test ob = new Test();
            ob.EmpID = 10;
            ob.show(10, 20);

            Test ob1 = new Test();                        
            ob1.show("Rajesh",20);
        }
    }
}

Thursday, April 21, 2011

Save Successfully confirm message using store procedure(sp) Input OutPut

Insert,Update,Delete Store Procedure(SP) execution Successfully done or any Error that Can using output variable in sp.
Here I have Given Example For Insert Sp in Three Tier Architecture.


Insert Store Procedure
ALTER PROCEDURE dbo.sp_InserttblEmp @Name varchar(50), @depid int, @Salary int, @status int output AS insert into tblemp VALUES(@Name,@depid,@Salary); select @status=@@ERROR RETURN @status
LogicLayer.cs
public Boolean insert_tblemp(LogicLayer objLogicLayer)
    {
        int status;
        string Sp = "sp_InserttblEmp";
        objCmd = new SqlCommand(Sp,objCn);
        objCmd.CommandType = CommandType.StoredProcedure;
        objCmd.Parameters.Add("@Name",objLogicLayer.Name);
        objCmd.Parameters.Add("@depid", objLogicLayer.Sid);
        objCmd.Parameters.Add("@Salary", objLogicLayer.Salary);
        objCmd.Parameters.Add("@status", SqlDbType.Int).Value=1;
        objCmd.Parameters["@status"].Direction = ParameterDirection.InputOutput;
        objCn.Open();
        objCmd.ExecuteNonQuery();
        status = (int)objCmd.Parameters["@status"].Value;
        objCn.Close();
        if (status == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
DataLayer.cs
public class public class LogicLayer
{
{
DataLayer objLogicLayer=new LogicLayer ();
public int Sid { set; get; }
public string Name { set; get; }
public int Salary { set; get; }
public Boolean insert_tblemp(DataLayer objDataLayer)
{
return objLogicLayer.insert_tblemp(objDataLayer);
}
}
InsertForm.ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %>

<!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">
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td>
    Name
    </td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    depid
    </td>
    <td>
        <asp:TextBox ID="txtdepid" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Salary
    </td>
    <td>
        <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
   &nbsp;
        <asp:Label ID="lblMsg" runat="server" ForeColor="Red" Text="Label"></asp:Label>
    </td>
    <td>
        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
    </td>
    </tr>
    </table>
    </div>
    </form>
</body>
</html>
InsertForm.ASPX.cs
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 insert : System.Web.UI.Page
{
    LogicLayer objLogicLayer = new LogicLayer();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        { 
        
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool status;
        objLogicLayer.Sid = Convert.ToInt32(txtdepid.Text);
        objLogicLayer.Name = txtName.Text;
        objLogicLayer.Salary = Convert.ToInt32(txtSalary.Text);
        status = objLogicLayer.insert_tblemp(objLogicLayer);
        if (status == true)
        {
            lblMsg.Text = "Save Successfully";
        }
        else
        {
            lblMsg.Text = "Error";
        }
    }
}

Thursday, April 14, 2011

Date Validation in Formate dd/mm/yyyy in asp.net

DateValidation.aspx


<asp:textbox id="txtdate" runat="server"></asp:textbox>


<asp:regularexpressionvalidator controltovalidate="txtdate" errormessage="RegularExpressionValidator" 
id="RegularExpressionValidator1" runat="server"
validationexpression=
"(0[1-9]|[1 2][0-9]|3[0 1]|)[-/.](0[1-9]|1[0 1 2])[-/.](19/20)\d\d ">
</asp:regularexpressionvalidator>

Tuesday, April 5, 2011

SQL Update Query With inner Join and case

tblEMp

EmpID

Name

Salary

DepID

1

Sachin

1000

1

2

Mahora

2000

2

3

Afridi

3000

1

tblDep

DepID

DepName

1

D1

2

D2
Now

Now Question is Update Salary with 10% where DepName is D1.and 20% where DepName is D2. Use Join and Single Query Only.
Ans:-  update tblemp set Salary = Case tbldep.lname
           when 'D1' then Salary +(Salary*0.10)
          when 'D2' then Salary +(Salary*0.20)
          end
           from tblemp join tbldep on tblemp.depid=tbldep.depid

Wednesday, March 16, 2011

JavaScript return Value to Label or TextBox

Here Example of Email Validation is given

function Email(obj1)
{
var email=obj1.value;
//alert(email);
var reguex=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
if(reguex.test(email))
{
return true;
}
else
{      

document.getElementById("lblemail").innerHTML="email not valid";

return false;
}
}



Friday, March 4, 2011

What is ADO.Net ?

ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file.

Tuesday, January 18, 2011

Difference Between Eval And Bind in asp.net

Eval is Unidirectional where as Bind is Bi-Directional.
Eval can combine more than two filed where as Bind can not do this Operation.

Thursday, January 13, 2011

Why use Microsoft Sql server with Asp.net in Back end ?

There are many Database System Available e.g Microsoft Access, Oracle,Mysql,Microsoft SqlServer. The Main Point is that Microsoft SqlServer is Server So it can Handle multiple request at time. Oracle is also server but Microsoft SqlServer is in build install with .Net so with Oracle we need more Space that's why We Choice Microsoft SqlServer with ASP.NET Back End.

Password TextBox blank when Page Refresh or Button Click in asp.net

Password TextBox blank when Page Refresh or Button Click in asp.net
This is Very Series Problem when Register form Submit or Refresh Page or any DropDownList PostBack . Simple Solution of this Problem is

protected void Page_Load(object sender, EventArgs e)
{
txtPassword.Attributes.Add("Value", txtPassword.Text);

}
ASPdotNET-Example