Wednesday, 22 February 2012

How to View one record per page in ASP.NET?





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

<!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:TextBox ID="txtProductName" runat="server" 
 OnDataBinding="txtDataBind"></asp:TextBox>
           <asp:TextBox ID="txtProductid" runat="server"></asp:TextBox>
           <asp:Button ID="btnPrevious" runat="server" Text="Previous" 
 OnClick="PrevBtn"></asp:Button>
           <asp:Button ID="btnNext" runat="server" Text="Next" 
OnClick="NextBtn"></asp:Button>
       </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 SinglePage : System.Web.UI.Page
{
   DataTable dt;
   protected void Page_Load(object sender, EventArgs e)
   {
 dt = GetDataTable() as DataTable;

       if (!Page.IsPostBack)
       {
           ViewState["CurrentPos"] = 0;
           this.DataBind();
       }
   }
   protected void PrevBtn(object sender, System.EventArgs e)
   {
       try
       {
           int CurrentPos = (int)ViewState["CurrentPos"];
           if (CurrentPos > 0)
           {
               CurrentPos -= 1;
           }
           ViewState["CurrentPos"] = CurrentPos;
           this.DataBind();
       }
       catch (Exception ex)
       {
           Response.Write(ex.Message);
       }
   }

   protected void NextBtn(object sender, System.EventArgs e)
   {
       try
       {
           int CurrentPos = (int)ViewState["CurrentPos"];
           CurrentPos += 1;
           if (CurrentPos > dt.Rows.Count)
           {
               CurrentPos -= 1;
           }
           ViewState["CurrentPos"] = CurrentPos;
           this.DataBind();
       }
       catch (Exception ex)
       {
           Response.Write(ex.Message);
       }
   }

   protected void txtDataBind(Object sender, System.EventArgs e)
   {
       try
       {
           int CurrentPos = (int)ViewState["CurrentPos"];
           ViewState["CurrentPos"] = CurrentPos;
           txtProductid.Text = dt.Rows[CurrentPos]["productid"].ToString();
           txtProductName.Text = dt.Rows[CurrentPos]["productname"].ToString();
       }
       catch (Exception ex)
       {
           Response.Write(ex.Message);
       }
   }
   private DataTable GetDataTable()
   {
       //create table
       DataTable dt = new DataTable("Product");
       dt.Columns.Add("ProductID", Type.GetType("System.Int32"));
       dt.Columns.Add("ProductName", Type.GetType("System.String"));
    
       //create fields
       DataColumn[] pk = new DataColumn[1];
       pk[0] = dt.Columns["ProductID"];
       dt.PrimaryKey = pk;
       dt.Columns["ProductID"].AutoIncrement = true;
       dt.Columns["ProductID"].AutoIncrementSeed = 1;
       dt.Columns["ProductID"].ReadOnly = true;

       //fill rows
       DataRow dr;
       for (int x = 1; x <= 10; x++)
       {
           //make every other one different
           if (Math.IEEERemainder(x, 2) == 0)
           {
               dr = dt.NewRow();
               dr["ProductName"] = "Riss";
             
               dt.Rows.Add(dr);
           }
           else
           {
               dr = dt.NewRow();
               dr["ProductName"] = "Product";
           
               dt.Rows.Add(dr);

           }
       }

       return dt;
   }
}

Working With PopUp In ASP.net



Whenever we build any web applications it can have requirements to work with popup windows. For example: To pick a date for a date field in an aspx page, we can place a calendar control on a popup so that user can select a date from the calendar instead of typing himself, a simple date picker control. This article will help you understand some of tasks that we more often do with popup windows.

Refreshing a parent page from a popup ASP.Net page

There are situations where we will be required to populate the information’s entered on the popups to the parent page and refresh the parent page so that it can be accessed in the server side. The below example will help us in achieving it.

The below example will populate the entered name in the child.aspx(popup) to the parent(Parent.aspx) and submit the page to the server.
Parent.aspx

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

<!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>
<title>Untitled Page</title>

<script language="javascript">

function OpenWindow(strChildPageUrl)

{

   var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,
                       top=0,left=0,scrollbars=1");

}

</script>

</head>
<body>
<form runat="Server">
<div>
   <asp:textbox id="txtName" runat="server"></asp:textbox>
   <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" 
                 Text="Get Value" />
   <input type="button" id="Button1" value="Enter Name"  
                    onclick="OpenWindow('Child.aspx')" />
</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 Parent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
    }

}
protected void Button2_Click(object sender, EventArgs e)
{
    if (txtName.Text != "")

        Response.Write(txtName.Text);

}
}

child.aspx


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

<!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 language="javascript">

 function SubmitToParent()

 {

 window.opener.document.forms[0].txtName.value =
                 document.getElementById('txtChildName').value;

 window.opener.document.forms[0].submit();

 self.close();

 }

</script>

</head>
<body>
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtChildName" runat="server"></asp:TextBox>
        <input type="button" id="Button1" value="Submit to Parent" 
                   onclick="SubmitToParent()" />
    </div>
</form>
</body>
</html>
Window.Open Clears Parent page and writes [Object]

Sometimes we will have requirements to open an asp.net page as a popup
 when we click a hyperlink. Consider the below code,



<a href="javascript:window.open('http:/google.com')"> google</a>



The above code will clear the existing content on the page and will 
output only [Object]. This behaviour is because the actual return value of
Window.Open function is the window object itself.

To prevent the above behaviour and have the parent page without 
clearing its existing content we need to change the above code similar to below,



<a href="javascript:void(window.open('http:/google.com'))"> google</a>

or

<a href="#" onclick="javascript:window.open('http:/google.com');
 return false;"> google</a>
Opening ASP.Net Popup window in specific location of the screen


Opening ASP.Net Popup window in specific location of the screen



Sometimes we would like to open our popup window on 
specific location on our screen. This can be done by MoveTo()
 method of the window object.



function OpenWindow(strChildPageUrl)

{

var testwindow = window.open(strChildPageUrl,"Child",
"width=400px,height=400px,top=0,left=0,scrollbars=1");

      testwindow.moveTo(100,0);

}

Select a row in an asp:GridView without using a Select Command




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

<!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="GridView1" runat="server" 
               AutoGenerateColumns="False" DataKeyNames="ID"
               Width="200px" AllowPaging="True" 
                   OnRowDataBound="PeopleGridView_RowDataBound">
               <Columns>
                   <asp:BoundField DataField="StringField" 
                              HeaderText="Name" SortExpression="StringField">
                   </asp:BoundField>
               </Columns>
           </asp:GridView>
       </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 SelectRow : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetDataSet();
            GridView1.DataBind();
        }

    }
    public DataTable GetDataSet()
    {

        DataTable dt = new DataTable("Company");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
        dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringField", typeof(string)));
        for (int i = 0; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i;
            dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
            dt.Rows.Add(dr);
            DataColumn[] Parent_PKColumns = new DataColumn[1];
            Parent_PKColumns[0] = dt.Columns["ID"];
            dt.PrimaryKey = Parent_PKColumns;
            Session["DataSource"] = dt;
        }

        return dt;
    }
    protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = 
                                          "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            e.Row.Attributes["onclick"] = 
                      ClientScript.GetPostBackClientHyperlink(this.GridView1,  
                            "Select$" + e.Row.RowIndex);
        }

    }
}

Passing Date from Calendar Pop-Up to Parent Window





This section will help us building a simple DatePicker control using Calendar control and Javascript. Create two aspx pages, ParentPage.aspx and Calendar.aspx. Calendar.aspx will contain a Calendar control and it should be opened as a popup window. When the user selects a date in the Calendar popup it will populate the date selected into a textbox in the ParentPage.aspx page.

ParentPage.aspx

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



<!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 type="text/javascript">

 function PopupPicker(ctl)

{

var PopupWindow=null;

PopupWindow=window.open('Calender.aspx?ctl='+ctl,'','width=250,height=250');

PopupWindow.focus();

}

 </script>



</head>

<body>

 <form id="form1" runat="server">

     <div>

         <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>

         <input id="Button2" type="button" value="Click" 
                                   onclick="PopupPicker('txtDate');" />

     </div>

 </form>

</body>

</html>



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



<!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 type="text/javascript">

  function SetDate(dateValue,ctl)



  {



      thisForm = window.opener.document.forms[0].elements[ctl].value= dateValue;

      self.close();

  }

  </script>



</head>

<body>

  <form id="form1" runat="server">

      <div>

          <asp:Calendar ID="Cal1" runat="Server" OnDayRender="Cal1_DayRender">
           </asp:Calendar>

      </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 Calender : System.Web.UI.Page

{

  string ctrl;

  protected void Page_Load(object sender, EventArgs e)

  {

      ctrl = Request.QueryString["ctl"].ToString();

  }



  protected void Cal1_DayRender(object sender, DayRenderEventArgs e)

  {

   

      HyperLink hpl = new HyperLink();

      hpl.Text = ((LiteralControl)e.Cell.Controls[0]).Text;

      hpl.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString() 
                                                 + "','" + ctrl + "');";

      e.Cell.Controls.Clear();

      e.Cell.Controls.Add(hpl);



  }

}
By default, the days in calendar control is rendered as links and generate a postback when it is clicked. Instead of postback, we will call our custom SetDate() JavaScript function by changing the cell of the Calendar control to Hyperlink control and attaching the SetDate() JavaScript function to the hyperlink in clnDatePicker_DayRender event.

The null coalescing operator: ??

This is a new feature of c# 2.0. The null coalescing operator is a short cut for checking if a value is null and if so returning the value of the second operand. Kind of like an IIF. The syntax is as follows 

string newValue = someValue ?? "default";
 
The first operand someValue must be a nullable type. The above code will set the value of newValue to someValue unless it's null, then it'll set it to "default".

You could also use this inline:

 
Console.WriteLine("The value is " + (someValue ?? "null"));

another use
return (bool)(ViewState["IsPaged"] ?? true);

How To Read Excel File and Display Data In GridView

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

<!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="GridView1" runat="server">
      </asp:GridView>

  </div>
      <asp:Button ID="btnRead" runat="server" 
Text="Read" OnClick="btnRead_Click" />
  </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 System.Data.OleDb;
using System.Diagnostics;

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

  }
  protected void btnRead_Click(object sender, EventArgs e)
  {
      try
      {
          OleDbConnection con = 
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\Test.xls;
Extended Properties=Excel 8.0");
          OleDbDataAdapter da =
new OleDbDataAdapter("select *from  [Sheet1$]", con);
          DataSet ds = new DataSet();
          da.Fill(ds);
          GridView1.DataSource = ds;
          GridView1.DataBind();
      }
      catch(Exception ex)
      {

          StackTrace trace = new StackTrace(ex,true);
      
          System.Text.StringBuilder sb = new System.Text.StringBuilder();
          sb.Append(trace.GetFrame(0).GetMethod().Name);
          sb.Append("Line: " + trace.GetFrame(0).GetFileLineNumber());
          sb.Append("Column: " + trace.GetFrame(0).GetFileColumnNumber());
          Response.Write(sb.ToString());
      }

  }
}

How To Add Client Side Validation in AjaxEnabled Site






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

<!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 runat="server">
  <title>Untitled Page</title>

  <script language="javascript" type="text/javascript">
function validate()
{
    if (document.getElementById("<%=txtName.ClientID%>").value=="")
    {
               alert("Name Feild can not be blank");
               document.getElementById("<%=txtName.ClientID%>").focus();
               return false;
    }
    if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
    {
               alert("Email id can not be blank");
              document.getElementById("<%=txtEmail.ClientID %>").focus();
              return false;
    }
   var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
   var emailid=document.getElementById("<%=txtEmail.ClientID %>").value;
   var matchArray = emailid.match(emailPat);
   if (matchArray == null)
  {
             alert("Your email address seems incorrect. Please try again.");
             document.getElementById("<%=txtEmail.ClientID %>").focus();
             return false;
  }
  if(document.getElementById("<%=txtWebURL.ClientID %>").value=="")
  {
             alert("Web URL can not be blank");
             document.getElementById("<%=txtWebURL.ClientID %>").value="http://"
             document.getElementById("<%=txtWebURL.ClientID %>").focus();
             return false;
  }
  var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
  var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;
  var matchURL=tempURL.match(Url);
   if(matchURL==null)
   {
             alert("Web URL does not look valid");
             document.getElementById("<%=txtWebURL.ClientID %>").focus();
             return false;
   }
   if (document.getElementById("<%=txtZIP.ClientID%>").value=="")
   {
             alert("Zip Code is not valid");
             document.getElementById("<%=txtZIP.ClientID%>").focus();
             return false;
   }
   var digits="0123456789";
   var temp;
   for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>").value.length;i++)
   {
             temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);
             if (digits.indexOf(temp)==-1)
             {
                      alert("Please enter correct zip code");
                      document.getElementById("<%=txtZIP.ClientID%>").focus();
                      return false;
             }
   }
   return true;
}
  </script>

</head>
<body>
  <form id="form1" runat="server">
      <asp:ScriptManager ID="ScriptManager1" runat="server" />
      <div>
          <asp:UpdatePanel ID="UpdatePanel1" runat="server">
              <ContentTemplate>
                  <table>
                      <tr>
                          <td>
                              Name</td>
                          <td>
                              <asp:TextBox ID="txtName" runat="Server" />
                          </td>
                          <td>
                              Email</td>
                          <td>
                              <asp:TextBox ID="txtEmail" runat="Server" />
                          </td>
                          <td>
                              URL</td>
                          <td>
                              <asp:TextBox ID="txtWebURL" runat="Server" /></td>
                          <td>
                              Zip</td>
                          <td>
                              <asp:TextBox ID="txtZIP" runat="Server" />
                          </td>
                      </tr>
                  </table>
                  <asp:Button ID="DoButton" OnClick="DoButton_Click" runat="server" Text="Do something" />
              </ContentTemplate>
          </asp:UpdatePanel>
      </div>
  </form>
</body>
</html>


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

    }
    protected void DoButton_Click(object sender, EventArgs e)
    {
        //Do something on server side.
       
        string scripttext = "validate()";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "close", scripttext, true);

    }
}

How To Add Tooltip in GridView






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

<!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 language="JavaScript">
<!--

var bname;
var bversion;
var brows;

function reg()
{
bname=navigator.appName;
bversion=parseInt(navigator.appVersion)
if (bname=="Netscape")
brows=true
else
brows=false
}

// Do not edit anything else in the script !!!!

function don(row,path){
if ((bname=="Netscape" && bversion>=4) ||
 (bname=="Microsoft Internet Explorer" && bversion>=4)){
if (brows){

document.layers['linkex'].document.writeln('<img src='+path+' />');
document.layers['linkex'].document.close();
 var rec = getoffset(row);
document.layers['linkex'].top=rec.Top+row.offsetTop;
document.layers['linkex'].left=rec.Left;

document.layers['linkex'].visibility="show";
}
else
 {
//debugger;
linkex.innerHTML='<img src='+path+' />';
var rec = getoffset(row);
linkex.style.top=rec.Top+row.offsetHeight;
linkex.style.left=rec.Left;
//linkex.style.background=bgcolor;

linkex.style.visibility="visible";
}
}
}

function doff(){
if ((bname=="Netscape" && bversion>=4) ||
 (bname=="Microsoft Internet Explorer" && bversion>=4)){
if (brows)
document.layers['linkex'].visibility="hide";
else
linkex.style.visibility="hidden";
}
}

function   getoffset(e)
{  
var   t=e.offsetTop;  
var   l=e.offsetLeft;  
while(e=e.offsetParent)
{  
t+=e.offsetTop;  
l+=e.offsetLeft;  
}  
var   rec   = new Object();

rec.Top   =   t;
rec.Left  =   l;

return   rec
}

//-->


  </script>

</head>
<body onload='reg();'>
  <form id="form1" runat="server">
      <div id="linkex" style="position: absolute; visibility: hidden; width: 80%">
      </div>
      <layer name="linkex" visibility="hide" width="80%:">
     </layer>
      <div>
          <asp:GridView ID="GridView1" runat="server" 
                          OnRowDataBound="GridView1_RowDataBound">
          </asp:GridView>
      </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 tooltip : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
           bind();
   }

   private void bind()
   {
       DataTable table = new DataTable();
       table.Columns.Add("booktitle");
       table.Columns.Add("tooltip");


       DataRow dr = table.NewRow();
       dr["booktitle"] = "aaaaa";
       dr["tooltip"] = "cart_icon.jpg";
       table.Rows.Add(dr);
       DataRow dr1 = table.NewRow();
       dr1["booktitle"] = "ddd";
       dr1["tooltip"] = "cart_icon2.jpg";
       table.Rows.Add(dr1);
       this.GridView1.DataSource = table;
       GridView1.DataBind();
   }

   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
   {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           DataRowView drv = ((DataRowView)e.Row.DataItem);
           string path = drv["tooltip"].ToString();
           e.Row.Attributes.Add("onmouseover", "don(this,'" + path + "')");
           e.Row.Attributes.Add("onmouseout", "doff()");
       }
   }
}

Tuesday, 21 February 2012

Abstract Class versus Interface

Abstract Class versus Interface

 

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.
I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.
In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Abstract Class Employee

 

using System;

namespace AbstractsANDInterfaces
{
    /// 

    /// Summary description for Employee.
    /// 
    
    public abstract class Employee
    {
        //we can have fields and properties 

        //in the Abstract class
        protected String id;
        protected String lname;
        protected String fname;

        //properties

        public abstract String ID
        {
            get;
            set;
        }

        public abstract String FirstName
        {
            get;
            set;
        }
        
        public abstract String LastName
        {
            get;
            set;
        }
        //completed methods

        public String Update()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " updated";
        }
        //completed methods

        public String Add()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " added";
        }
        //completed methods

        public String Delete()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " deleted";
        }
        //completed methods

        public String Search()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " found";
        }

        //abstract method that is different 

        //from Fulltime and Contractor
        //therefore i keep it uncompleted and 
        //let each implementation 
        //complete it the way they calculate the wage.

        public abstract String CalculateWage();
        
    }


}
 
 
 
 
 

Interface Employee

 

 

using System;


namespace AbstractsANDInterfaces
{
    /// <summary>

    /// Summary description for IEmployee.
    /// </summary>
    public interface IEmployee
    {
        //cannot have fields. uncommenting 

        //will raise error!        //        protected String id;        //        protected String lname;        //        protected String fname;

        //just signature of the properties 
        //and methods.
        //setting a rule or contract to be 
        //followed by implementations.

        String ID
        {
            get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
        
        String LastName
        {
            get;
            set;
        }
        
        // cannot have implementation

        // cannot have modifiers public 
        // etc all are assumed public
        // cannot have virtual

        String Update();

        String Add();

        String Delete();

        String Search();

        String CalculateWage();
    }
}

 

Inherited Objects

Emp_Fulltime:

using System;

namespace AbstractsANDInterfaces
{
    /// 

    /// Summary description for Emp_Fulltime.
    /// 
     
    //Inheriting from the Abstract class
    public class Emp_Fulltime : Employee
    {
        //uses all the properties of the 

        //Abstract class therefore no 
        //properties or fields here!

        public Emp_Fulltime()
        {
        }


        public override String ID
        {
            get

            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        
        public override String FirstName
        {
            get

            {
                return fname;
            }
            set
            {
                fname = value;
            }
        }

        public override String LastName
        {
            get

            {
                return lname;
            }
            set
            {
                lname = value;
            }
        }

        //common methods that are 
        //implemented in the abstract class
        public new String Add()
        {
            return base.Add();
        }
        //common methods that are implemented 

        //in the abstract class
        public new String Delete()
        {
            return base.Delete();
        }
        //common methods that are implemented 

        //in the abstract class
        public new String Search()
        {
            return base.Search();
        }
        //common methods that are implemented 

        //in the abstract class
        public new String Update()
        {
            return base.Update();
        }
        
        //abstract method that is different 

        //from Fulltime and Contractor
        //therefore I override it here.
        public override String CalculateWage()
        {
            return "Full time employee " + 
                  base.fname + " is calculated " + 
                  "using the Abstract class...";
        }
    }
}
 
 
 
Emp_Fulltime2:
 
 
 
using System;

namespace AbstractsANDInterfaces
{
    /// 
    /// Summary description for Emp_fulltime2.

    /// 
    
    //Implementing the interface
    public class Emp_fulltime2 : IEmployee
    {
        //All the properties and 

        //fields are defined here!
        protected String id;
        protected String lname;
        protected String fname;

        public Emp_fulltime2()
        {
            //


            // TODO: Add constructor logic here
            //

        }

        public String ID
        {
            get

            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        
        public String FirstName
        {
            get
            {
                return fname;
            }
            set

            {
                fname = value;
            }
        }

        public String LastName
        {
            get
            {
                return lname;
            }
            set
            {
                lname = value;
            }
        }

        //all the manipulations including Add,Delete, 

        //Search, Update, Calculate are done
        //within the object as there are not 
        //implementation in the Interface entity.
        public String Add()
        {
            return "Fulltime Employee " + 
                          fname + " added.";
        }

        public String Delete()
        {
            return "Fulltime Employee " + 
                        fname + " deleted.";
        }

        public String Search()
        {
            return "Fulltime Employee " + 
                       fname + " searched.";
        }

        public String Update()
        {
            return "Fulltime Employee " + 
                        fname + " updated.";
        }
        
        //if you change to Calculatewage(). 

        //Just small 'w' it will raise 
        //error as in interface
        //it is CalculateWage() with capital 'W'.
        public String CalculateWage()
        {
            return "Full time employee " + 
                  fname + " caluculated using " + 
                  "Interface.";
        }
    }
} 


Code for Testing

 

//This is the sub that tests both 
//implementations using Interface and Abstract
private void InterfaceExample_Click(object sender, 
                                System.EventArgs e)
{
    try

    {

        IEmployee emp;

        Emp_fulltime2 emp1 = new Emp_fulltime2();

        emp =  emp1;
        emp.ID = "2234";
        emp.FirstName= "Rahman" ;
        emp.LastName = "Mahmoodi" ;
        //call add method od the object

        MessageBox.Show(emp.Add().ToString());
        
        //call the CalculateWage method
        MessageBox.Show(emp.CalculateWage().ToString());


    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

private void cmdAbstractExample_Click(object sender, 
                                   System.EventArgs e)
{

    Employee emp;

    emp = new Emp_Fulltime();
    

    emp.ID = "2244";
    emp.FirstName= "Maria" ;
    emp.LastName = "Robinlius" ;
    MessageBox.Show(emp.Add().ToString());

    //call the CalculateWage method

    MessageBox.Show(emp.CalculateWage().ToString());

}
 

Conclusion

In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.
 

 


 

 

Hidden Features of C#?

Hidden Features of C# ?

Here are the revealed features so far:



Keywords

Attributes

Syntax

Language Features

Visual Studio Features

Framework

Methods and Properties

Tips & Tricks

  • Nice method for event handlers by Andreas H.R. Nilsson
  • Uppercase comparisons by John
  • Access anonymous types without reflection by dp
  • A quick way to lazily instantiate collection properties by Will
  • JavaScript-like anonymous inline-functions by roosteronacid

Other