How To display a JavaScript alert window during a partial postback, from code behind




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


<!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:ScriptManager ID="ScriptManger1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnRedirect" runat="server" Text="Redirect"
OnClick="btnRedirect_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>




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 AjaxError : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnRedirect_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "MyScript",
"alert(" + DateTime.Now.Millisecond + ");", true);
//Code For Async Redirect
// ScriptManager.RegisterStartupScript(Page, GetType(), "MyScript1",
"javascript:window.location.href='Default.aspx'",true);


}
}

How to detect browser closing and navigating to some other page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
<script type="text/jscript">
var leaving=true;
window.onbeforeunload = function(e)
{
      if (!e) e = event;
      if (leaving) e.returnValue = "You might loose your changes";
}

</script>
  <title></title>
  </head>
  <body>
  <a href="http://www.google.com/">Leave</a>
<a href="page1.htm" onClick="leaving=false">stay on site</a>

  </body>
</html>

Using a Class Factory to Create Objects— Single Factory




using System;
using System.Collections.Generic;
using System.Text;

namespace SampleFactoryClass
{
public interface IApparel // Interface representing product
{

string ShowMe();

bool Knit // Property to indicate if Knit

{ get; }

}

public class SportsShirt : IApparel
{

public string ShowMe()
{

return ("Sports Shirt");

}

public bool Knit

{ get { return true; } }

}

public class DressShirt : IApparel
{

public string ShowMe()
{

return ("Dress Shirt");

}

public bool Knit

{ get { return false; } }

}

// Factory to return instances of apparel classes

public class ApparelFactory
{

public IApparel CreateApparel(string apptype)
{

switch (apptype)
{

case "MDRSHIRT":

return new DressShirt();

case "MSPSHIRT":

return new SportsShirt();

}

return null;

}
public static void Main()
{

ApparelFactory factory = new ApparelFactory();

IApparel ob1 = factory.CreateApparel("MDRSHIRT");

IApparel ob2 = factory.CreateApparel("MSPSHIRT");

string shirtType = ob1.ShowMe(); // Returns "Dress Shirt"
Console.WriteLine(shirtType);
Console.Read();





}

}


}

How To Insert A New Row In GridView

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView AutoGenerateColumns="False" ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
               OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand">
               <Columns>
                   <asp:TemplateField ShowHeader="False">
                       <EditItemTemplate>
                           <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                               Text="Update"></asp:LinkButton>
                           <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                               Text="Cancel"></asp:LinkButton>
                       </EditItemTemplate>
                       <FooterTemplate>
                           <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Insert">Insert</asp:LinkButton>
                       </FooterTemplate>
                       <ItemTemplate>
                           <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                               Text="Edit"></asp:LinkButton>
                       </ItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField>
                       <FooterTemplate>
                           <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                       </FooterTemplate>
                       <ItemTemplate>
                           <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
                       </ItemTemplate>
                       <EditItemTemplate>
                           <asp:TextBox ID="txtID" runat="server" Text='<%#Bind("ID") %>'></asp:TextBox>
                       </EditItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField HeaderText="Name">
                       <FooterTemplate>
                           <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                       </FooterTemplate>
                       <ItemTemplate>
                           <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                       </ItemTemplate>
                       <EditItemTemplate>
                           <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>'></asp:TextBox>
                       </EditItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
       </div>
       <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" />
   </form>
</body>
</html>
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 InsertRowGridView : System.Web.UI.Page
{
   DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            BindGrid();

        }

    }

    private void BindGrid()
    {

        DataTable dt = new DataTable(); dt = (DataTable)Session["MyDataSource"];


        GridView1.DataSource = GetDataSource();

        GridView1.DataBind();

    }

    protected DataTable GetDataSource()
    {

        const string key = "MyDataSource";
        DataTable dt = Session[key] as DataTable;

        if (dt == null)
        {

            dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));

            dt.Columns.Add("Name", typeof(string));
            dt.Rows.Add("1", "first object");

            dt.Rows.Add("2", "second object");
            Session[key] = dt;

        }

        return dt;
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

        GridView1.EditIndex = e.NewEditIndex;

        BindGrid();

    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

        GridView1.EditIndex = -1;

        BindGrid();

    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        GridViewRow row = GridView1.Rows[e.RowIndex];
        GridView1.EditIndex = -1;

        if (row != null)
        {

            TextBox txtID = GridView1.Rows[e.RowIndex].Cells[0].FindControl("txtID") as TextBox;
            TextBox txtName = GridView1.Rows[e.RowIndex].Cells[1].FindControl("txtName") as TextBox;

            dt = (DataTable)Session["MyDataSource"];



            for (int i = 0; i < dt.Rows.Count; i++)
            {

                if (e.RowIndex == i)
                {

                    dt.Rows[i][1] = txtName.Text;

                    dt.Rows[i][0] = Convert.ToInt32(txtID.Text);


                    Session["MyDataSource"] = dt;

                    GridView1.DataSource = dt;
                    GridView1.DataBind();

                }

            }

        }

    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Insert")
        {
            // these are alternate ways of getting to grid
            //GridView gv = sender as GridView;
            //GridView gv = (GridView)sender;
            AddData();

            GridView1.ShowFooter = false;
            BindGrid();
           
            btnAdd.Enabled = true;
        }
    }

    protected void AddData()
    {
        DataTable  dt = (DataTable)Session["MyDataSource"];
        DataRow rw = dt.NewRow();
        TextBox txt = (TextBox)GridView1.FooterRow.Cells[1].FindControl("TextBox1");
        rw[0] = Convert.ToInt32(txt.Text);
        txt = (TextBox)GridView1.FooterRow.Cells[2].FindControl("TextBox2");
        rw[1] = txt.Text;
        dt.Rows.Add(rw);
        Session["MyDataSource"] = dt;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        GridView1.ShowFooter = true;
        BindGrid();

        btnAdd.Enabled = false;
    }
}


how to access and invoke private methods,fields or properties

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTe
{
    /// <summary>
    /// Holds blog information
    /// </summary>
    public class Blog
    {
        /// <summary>
        /// Gets the posts count.
        /// </summary>
        private static int PostsCount
        {
            get
            {
                return 10000;
            }
        }

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <returns></returns>
        private string GetDescription()
        {
            return @"A weblog dedicated to obsessively profiling
reviewing new Internet products and companies";
        }


        /// <summary>
        /// Changes the name of the blog.
        /// </summary>
        /// <param name="newName">The new name.</param>
        private string ChangeBlogName(string newName)
        {
            name = newName;
            return name;
        }


        string url = "http://techcrunch.com";
        string name = "Tech Crunch";
    }
    class Program
    {
        static void Main(string[] args)
        {



            Blog blog = new Blog();
            Type type = typeof(Blog);
            //create reflection bindings - will be used to retrive private fields,methods or properties
            BindingFlags privateBindings = BindingFlags.NonPublic | BindingFlags.Instance;

            // retrive private fields from our class
            FieldInfo[] fieldInfos = type.GetFields(privateBindings);

            // retrive private fields metadata
            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                Console.WriteLine(fieldInfo.Name + " " + fieldInfo.GetValue(blog));
            }


            PropertyInfo[] propertyInfos = type.GetProperties(privateBindings | BindingFlags.Static);
            // retrive private static properties metadata
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                // note that no instance need for static property to retrive it's value
                Console.WriteLine(propertyInfo.Name + " " + propertyInfo.GetValue(null, null));
            }

            // call method using MethodInfo object
            MethodInfo miGetDescription = type.GetMethod("GetDescription", privateBindings);
            object retObj = miGetDescription.Invoke(blog, new object[] { });
            Console.WriteLine(retObj);

            // call method using MethodInfo object with input parameters
            MethodInfo miChangeBlogName = type.GetMethod("ChangeBlogName", privateBindings);
            retObj = miChangeBlogName.Invoke(blog, new object[] { "Yahoo blog" });
            Console.WriteLine(retObj);

            Console.ReadLine();



        }
    }
}

Cancelling an Asynchronous Request




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


<!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">
<asp:ScriptManager ID="S1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<%= System.DateTime.Now.ToLongTimeString() %>
<asp:Button ID="btnRefresh" runat="server" Text="Update"
OnClick="btnRefresh_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

<script type="text/javascript">
Sys.Application.add_init(Init);
var prm = null;

function Init(sender)
{
prm = Sys.WebForms.PageRequestManager.getInstance();
//Ensure EnablePartialRendering isn't false which will prevent
//accessing an instance of the PageRequestManager
if (prm)
{
if (!prm.get_isInAsyncPostBack())
{
prm.add_initializeRequest(InitRequest);
}
}
}
function InitRequest(sender,args)
{

if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'btnRefresh') {
//Could abort current request by using: prm.abortPostBack();
//Cancel most recent request so that previous request will complete
//and display
args.set_cancel(true);
alert("A request is currently being processed. Please " +
"wait before refreshing again.");
}
}
</script>

</body>
</html>


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 AjaxCancel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
protected void btnRefresh_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
}

How to Raise Events for FILEUPLOAD Control

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

<!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 type="text/javascript">
function GetFileName(val)
{
   var i = val.lastIndexOf("\\");
   return val.substring(i+1);
}
   </script>

   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:FileUpload ID="FileUpload1" runat="server" size="40"
onchange="this.form.TextBox1.value=GetFileName(this.value);" />
           <asp:TextBox ID="TextBox1" runat="server" />
       </div>
   </form>
</body>
</html>

How To Create Templated Databound Controls




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


<%@ Register Namespace="BoundCustomControl" TagPrefix="custom"
Assembly="DataBoundControl" %>

<!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>
<style type="text/css">
.movies
{
width:500px;
}
.movies div
{
border:solid 1px black;
padding:10px;
margin:10px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<custom:DivView ID="a" runat="server" CssClass="movies">
<ItemTemplate>
<h1>
<%# Eval("Title") %>
</h1>
Director:
<%# Eval("Director") %>
</ItemTemplate>
</custom:DivView>
</div>
</form>
</body>
</html>




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 DivView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
a.DataSource = GetCustomMadeDataTable();
a.DataBind();
}
public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object

System.Data.DataTable objDataTable = new System.Data.DataTable();

//Create three columns with string as their type

objDataTable.Columns.Add("Id", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Director", typeof(string));
DataRow dr;
//Adding some data in the rows of this DataTable
for (int i = 0; i <= 50; i++)
{
dr = objDataTable.NewRow();
dr[0] = i.ToString();
dr[1] = "Title" + i.ToString();
dr[2] = "Director" + i.ToString();
objDataTable.Rows.Add(dr);





}

DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["dtTemp"] = objDataTable;
return objDataTable;
}
}




BoundCustomControl


using System;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace BoundCustomControl
{
public class DivView : CompositeDataBoundControl
{

private ITemplate _itemTemplate;

[TemplateContainer(typeof(DivViewItem)),
PersistenceMode(PersistenceMode.InnerProperty)]

public ITemplate ItemTemplate
{
get { return _itemTemplate; }
set { _itemTemplate = value; }
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource,
bool dataBinding)
{
int counter = 0;
foreach (object dataItem in dataSource)
{

DivViewItem contentItem = new DivViewItem(dataItem, counter);
_itemTemplate.InstantiateIn(contentItem);
Controls.Add(contentItem);
counter = counter + 1;
}
DataBind(false);
return counter;

}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}

}
public class DivViewItem : WebControl, IDataItemContainer
{
private object _dataItem;
private int _index;

public DivViewItem(object dataItem, int index)
{
_dataItem = dataItem;
_index = index;


}


object IDataItemContainer.DataItem
{
get { return _dataItem; }
}

int IDataItemContainer.DataItemIndex
{
get { return _index; }
}

int IDataItemContainer.DisplayIndex
{
get { return (int)_index; }
}

protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}

}

}

How To Add Dynamic AJAX Control Toolkit - Calendar Extender




<%@ Page Language="C#" AutoEventWireup="true"

CodeFile="DynamicAjaxExtender.aspx.cs"
Inherits="DynamicAjaxExtender" %>


<!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">
<asp:ScriptManager ID="ScriptManger1"
runat="server"></asp:ScriptManager>
<div>
<asp:PlaceHolder ID="placeHolder1"
runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Create" /></div>
</form>
</body>
</html>


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;
using AjaxControlToolkit;

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

}
protected void Button1_Click(object sender, EventArgs e)
{
// Create a textbox to hold the date
TextBox dateValue = new TextBox();
dateValue.ID = "dateValue";

// Create the calendar extender
AjaxControlToolkit.CalendarExtender ajaxCalendar =
new AjaxControlToolkit.CalendarExtender();
ajaxCalendar.ID = "ajaxCalendar";
ajaxCalendar.Format = "MM/dd/yyyy";
ajaxCalendar.TargetControlID = dateValue.ID;

placeHolder1.Controls.Add(dateValue);
placeHolder1.Controls.Add(ajaxCalendar);
}
}

How To Add Column Summery In GridView




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


<!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:GridView ID="grdMovies" OnRowDataBound="grdMovies_RowDataBound" AutoGenerateColumns="false"
ShowFooter="true" runat="server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Box Office Totals">
<ItemTemplate>
<%# Eval("SellPrice", "{0:c}")%>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblSummary" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>


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 DisplayColumnSummery : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
grdMovies.DataSource = GetData();
grdMovies.DataBind();

}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Movie");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = 1 * 3;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
int _boxOfficeTotalsTotal = 0;
protected void grdMovies_RowDataBound(object sender, GridViewRowEventArgs e)
{

if(e.Row.RowType==DataControlRowType.DataRow)
{

int boxOfficeTotals = int.Parse(DataBinder.Eval(e.Row.DataItem, "SellPrice").ToString());
_boxOfficeTotalsTotal += boxOfficeTotals;



}
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblSummary = (Label)e.Row.FindControl("lblSummary");
lblSummary.Text = string.Format("Total: {0:c}", _boxOfficeTotalsTotal);
}
}


}
}

How To Add Default Button(For IE and Mozila)

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

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
   <title>Untitled Page</title>
   <script type="text/javascript">
       function press(evt)
       {
           if(evt.which || evt.keyCode)
           {
               if ((evt.which == 13) || (evt.keyCode == 13))
               {
                
                   var buttonid = '<%=Button11.ClientID %>';
                   __doPostBack(buttonid,'');
                   return false;
               }
           }
           else
           {
               return true;
           }
       }
   </script>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:TextBox ID="TextBox11" runat="server"
onkeypress="press(event);"></asp:TextBox>
       <asp:Button ID="Button11" runat="server" Text="Button"
OnClick="Button11_Click" />
   </div>
   </form>
</body>
</html>



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 DefaultButton : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       ClientScript.GetPostBackEventReference(this, string.Empty);
   }

   protected void Button11_Click(object sender, EventArgs e)
   {
       Response.Write("button clicked");
   }
}

How To Handle an async postback timeout in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" %>

<script runat="server">
   protected void slow_postback(object sender, EventArgs e)
   {
       // ten seconds is overkill... we timeout after one second (see ScriptManager below) 
       System.Threading.Thread.Sleep(10000);
   }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Handling an async postback timeout</title>
</head>
<body>
   <form id="form1" runat="server">
       <!-- This sets the timeout on async postbacks (i.e. UpdatePanel refreshes) to one second -->
       <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="1" />
       <asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>
               <asp:Button ID="Button1" runat="server" Text="Fast postback - no timeout" /> <br />
               <asp:Button ID="Button2" runat="server"
                Text="Slow postback - times out after one second"
 OnClick="slow_postback" /> <br />
               Last updated: <%= DateTime.Now %>
           </ContentTemplate>
       </asp:UpdatePanel>
   </form>
</body>

<script type="text/javascript">
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) {
       if (args.get_error() && args.get_error().name ===
'Sys.WebForms.PageRequestManagerTimeoutException') {
           alert('Caught a timeout!');
           // remember to set errorHandled = true to keep from getting a
popup from the AJAX library itself 
           args.set_errorHandled(true);
       }
   });
</script>
</html>

GridView Tips and Trics

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Grid View Add Update Delete</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
              ShowFooter="true" AllowPaging="true"  PageSize="4"
              AllowSorting="True"
              OnRowCommand="GridView1_RowCommand"
              OnPageIndexChanging="GridView1_PageIndexChanging"
              OnRowDeleting="GridView1_RowDeleting"
              OnRowEditing="GridView1_RowEditing"
              OnRowUpdating="GridView1_RowUpdating"
              OnSorting="GridView1_Sorting"
              OnRowCancelingEdit="GridView1_RowCancelingEdit">
               <Columns>
                 <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                  <asp:TemplateField HeaderText="Id" InsertVisible="False" SortExpression="Id">
                      <EditItemTemplate>
                          <asp:Label ID="Label1" runat="server"
Text='<%# Eval("Id") %>'></asp:Label>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label1" runat="server"
Text='<%# Bind("Id") %>'></asp:Label>
                      </ItemTemplate>
                  </asp:TemplateField>
                   <asp:BoundField DataField="Id"  ShowHeader="True"/>
                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
                      <EditItemTemplate>
                          <asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("Name") %>'></asp:TextBox>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label2" runat="server"
 Text='<%# Bind("Name") %>'></asp:Label>
                      </ItemTemplate>
                      <FooterTemplate>
                          <asp:TextBox ID="QuantityTextBox" runat="server"></asp:TextBox>
                      </FooterTemplate>
                  </asp:TemplateField>
                  <asp:TemplateField HeaderText="Description" SortExpression="Description">
                      <EditItemTemplate>
                          <asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("Description") %>'></asp:TextBox>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label3" runat="server"
Text='<%# Bind("Description") %>'></asp:Label>
                      </ItemTemplate>
                      <FooterTemplate>
                          <asp:TextBox ID="DescriptionTextBox" runat="server"></asp:TextBox>
                      </FooterTemplate>
                  </asp:TemplateField>
                  <asp:TemplateField>
                     <FooterTemplate>
                          <asp:LinkButton ID="btnNew" runat="server"
CommandName="New" Text="New" />
                      </FooterTemplate>
                  </asp:TemplateField>
              </Columns>
          </asp:GridView>
       </div>
       <div style="color:Red">
       <asp:Label ID="lblMsg" runat="server"></asp:Label>
       </div>
   </form>
</body>
</html>
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 GridViewComplete : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!IsPostBack)
        {
            BindGrid();
          
        }
    }
    public void BindGrid()
    {


        if (Session["dt"] == null)
        {
            GridView1.DataSource = CreateDGDataSource();
            GridView1.DataBind();
        }
        else
        {

            GridView1.DataSource = Session["dt"] as DataTable;
            GridView1.DataBind();

        }



    }
    public DataTable CreateDGDataSource()
    {
        // Create sample data for the DataList control.
        DataTable dt = new DataTable();
        DataRow dr;
        int i;
        int y;
        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("ID", typeof(int)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Description", typeof(string)));
        //Make some rows and put some sample data in
        for (i = 1; i <= 5; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Name" + "-" + i;
            dr[2] = "Item " + "_" + i;
            //add the row to the datatable
            dt.Rows.Add(dr);
        }

        Session["y"] = i;
        Session["dt"] = dt;

        return dt;
    }

    public ICollection CreateDGDataSource(int CategoryID)
    {
        DataView dv = new DataView(CreateDGDataSource(), "ID=" + CategoryID, null,
            DataViewRowState.CurrentRows);
        return dv;

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.Equals("New"))
            {
                LinkButton btnNew = e.CommandSource as LinkButton;
                GridViewRow row = btnNew.NamingContainer as GridViewRow;
                if (row == null)
                {
                    return;
                }
                TextBox txtCatName = row.FindControl("QuantityTextBox") as TextBox;
                TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;
                DataTable dt = Session["dt"] as DataTable;
                DataRow dr;
                int intId = (int)Session["y"];
                dr = dt.NewRow();
                dr["Id"] = intId++;
                Session["y"] = intId;
                dr["Name"] = txtCatName.Text;
                dr["Description"] = txtDescription.Text;
                dt.Rows.Add(dr);
                dt.AcceptChanges();
                Session["dt"] = dt;

                GridView1.DataSource = Session["dt"] as DataTable;
                GridView1.DataBind();

            }

        }
        catch (Exception ex)
        {

        }


    }
   
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = Session["dt"] as DataTable;
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }
    private string ConvertSortDirectionToSql(SortDirection sortDireciton)
    {
        string newSortDirection = String.Empty;
        switch (sortDireciton)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;
            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }
        return newSortDirection;
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
        // Query the database and get the values based on the ID and delete it.
        lblMsg.Text = "Deleted Record Id" +ID.ToString();
      
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
       
        // Retrieve the row being edited.
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
        TextBox t1 = row.FindControl("TextBox1") as TextBox;
        TextBox t2 = row.FindControl("TextBox2") as TextBox;
        string t3 = GridView1.DataKeys[e.RowIndex].Value.ToString();

        lblMsg.Text = "Updated record " + t1.Text + "," + t2.Text + "Value From Bound Field" + t3;
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
}

How To get IP Address to Country/State using www.hostip.info

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;
using System.Net;
using System.Text;

public partial class IpInfo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ipUrl = "http://www.hostip.info/api/get.html?ip=" + Request.UserHostAddress;
       
       
        WebClient webClient = new WebClient();
        Byte[] ipInfoBytes = webClient.DownloadData(ipUrl);
        UTF8Encoding encoding = new UTF8Encoding();
        string ipInfo = encoding.GetString(ipInfoBytes);

        Response.Write(ipInfo);

    }
}

ModalPopupExtender Example for Editing Rows in a GridView (Master/Detail Scenario)

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>
<!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="form" runat="server">
       <asp:ScriptManager ID="scriptManager" runat="server" />
       <div>
           <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
               <ContentTemplate>
                   <asp:Label ID="lblTitle" runat="server" Text="Customers" BackColor="lightblue" Width="95%" />
                   <asp:GridView ID="gvCustomers" runat="server" DataKeyNames="Id" AutoGenerateColumns="false"
                       AllowPaging="true" AllowSorting="true" PageSize="10" Width="95%">
                       <AlternatingRowStyle BackColor="aliceBlue" />
                       <HeaderStyle HorizontalAlign="Left" />
                       <Columns>
                           <asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px">
                               <ItemTemplate>
                                   <asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClick="BtnViewDetails_Click" />
                               </ItemTemplate>
                           </asp:TemplateField>
                           <asp:BoundField DataField="Id" HeaderText="ID" SortExpression="Id" ReadOnly="true" />
                           <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="contactname" ReadOnly="true" />
                       </Columns>
                   </asp:GridView>
               </ContentTemplate>
           </asp:UpdatePanel>
           <asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
           <ajaxtoolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="btnShowPopup"
               PopupControlID="pnlPopup" CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
           <asp:Panel ID="pnlPopup" runat="server" Width="500px" Style="display: none">
               <asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
                   <ContentTemplate>
                       <asp:Label ID="lblCustomerDetail" runat="server" Text="Customer Detail" BackColor="lightblue"
                           Width="95%" />
                       <asp:DetailsView ID="dvCustomerDetail" runat="server" DefaultMode="Edit" Width="95%"
                           BackColor="white" />
                   </ContentTemplate>
               </asp:UpdatePanel>
               <div align="right" style="width: 95%">
                   <asp:Button ID="btnSave" runat="server" Text="Save"
OnClientClick="alert('Sorry, but I didnt implement save '); return false;"
                       Width="50px" />
                   <asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
               </div>
           </asp:Panel>
       </div>
   </form>
</body>
</html>
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 MasterDetail : System.Web.UI.Page
{
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {

        ds = Data();
        if (!this.IsPostBack)
        {
            if (Session["parent"] == null)
            {
                gvCustomers.DataSource = ds.Tables["Parent"];
                gvCustomers.DataBind();
            }
            else
            {
                gvCustomers.DataSource = Session["Parent"] as DataTable;
                gvCustomers.DataBind();

            }
        }

    }
    private DataSet Data()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));

        dt.Rows.Add(new object[] { 1, "aaaa" });
        dt.Rows.Add(new object[] { 2, "bbbb" });
        dt.Rows.Add(new object[] { 3, "cccc" });
        dt.TableName = "Parent";




        DataTable dtc = new DataTable();
        dtc.Columns.Add("Id", typeof(int));
        dtc.Columns.Add("Qul", typeof(string));

        dtc.Rows.Add(new object[] { 1, "aaaa" });
        dtc.Rows.Add(new object[] { 2, "bbbb" });
        dtc.Rows.Add(new object[] { 3, "bbbb" });
        dtc.TableName = "Child";


        DataSet ds = new DataSet();

        ds.Tables.Add(dt);
        ds.Tables.Add(dtc);
        Session["Parent"] = dt;

        return ds;

    }
    protected void BtnViewDetails_Click(object sender, EventArgs e)
    {
        //  get the gridviewrow from the sender so we can get the datakey we need
        Button btnDetails = sender as Button;
        GridViewRow row = (GridViewRow)btnDetails.NamingContainer;

        //  extract the id from the row whose details button originated the postback.
        //  grab the customerid and feed it to the customer details datasource
        //  finally, rebind the detailview
        DataView dv = new DataView(ds.Tables["Child"]);

        dv.RowFilter = "Id=" + Convert.ToString(this.gvCustomers.DataKeys[row.RowIndex].Value);
        dvCustomerDetail.DataSource = dv;
        dvCustomerDetail.DataBind();

        //  update the contents in the detail panel
        this.updPnlCustomerDetail.Update();
        //  show the modal popup
        this.mdlPopup.Show();
    }  
}