Thursday, October 21, 2010

Inheritance

As we all know, inheritance is just the hierarchical relationship between various classes.
Class from which another class is inheriting some methods is base class and the other one is known as derived class.

For ex:
Class AA
{ }

Class BB : AA
{ }

Here, AA is your base class and B is your derived class.

Now a very basic question:
When we create an object of derived class, which constructor gets called?
1. Of Base Class
2. Of Derived Class
3. Both
4. None

Let's try to figure it with this example:

class AA
{
public AA()
{
Console.WriteLine("In AA");
}
}

class BB : AA
{
public BB()
{
Console.WriteLine("In BB");
}
}

class CC : BB
{
public CC()
{
Console.WriteLine("In CC");
}
}

Here, class CC is inheriting class BB and class BB is inheriting class AA.

class Program
{
static void Main(string[] args)
{
CC c = new CC();
}
}

I just created an object of CC in another class.
Now which constructor will be called?

Here is the output :


In case of inheritance, derived class always calls base class constructor first and then its own constructor.
Here, object of CC called the constructor of BB and similarly BB calls its base class constructor i.e., AA.
so, the sequence of execution is:
AA constructor -> BB constructor -> CC constructor

Read More..

Const Keyword

Const is a keyword which can be use to declare fields. We can initialize Const variable only at the time of declaration and cant modify it at runtime.
We cant make a Const field as static.
Const fields are compile-time constants.

For ex:
I have a class which contains two const variables.
class TestConst
{
public const int a = 10;
public const int b = 7;
}

I have another class, where i have created an object of TestConst class.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TestConst.a);
Console.WriteLine(TestConst.b);
Console.ReadLine();
}
}

We cant access a const variable through object of class. We can always access a const variable with class name only.
Like : ClassName.ConstVariableName
Read More..

ReadOnly Modifier

ReadOnly is a modifier which can be use to declare fields. We can initialize readonly variable either at the time of declaration or through constructor.

ReadOnly fields can be used for runtime constants as we can declare value through constructors.

For ex:
I have a class which contains two readonly variables.
class TestReadOnly
{
public readonly int a = 10;
public readonly int b;

public TestReadOnly()
{
b = 15;
}

public TestReadOnly(int newB)
{
b = newB;
}
}

I have another class, where i have created an object of TestReadOnly class.
class Program
{
static void Main(string[] args)
{
TestReadOnly test = new TestReadOnly();
Console.WriteLine(test.a);
Console.WriteLine(test.b);
test = new TestReadOnly(20);
Console.WriteLine(test.b);
Console.ReadLine();
}
}

Whenever, I want to reassign the value to a readonly variable, I have to call the parametrized constructor of the class and pass the new value.
Read More..

Monday, October 11, 2010

BENEFITS OF XMLDATADOCUMENT OVER XMLDOCUMENT

Recently I came across a requirement, where I need to fetch the data from GridView and convert it to XML.
I had a predefined format of XML, in which I need to save the data :
<root>
<rec>
<amount />
<remark />
</rec>
<rec>
<amount />
<remark />
</rec>
</root>
Also, I have a checkbox in the first column of GridView. I have to fetch records for which checkbox is checked.

I can use either XMLDocument or XMLDataDocument for the same.

1. Using XMLDocument:XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(root);
foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
XmlElement rec = xmlDoc.CreateElement("rec");
root.AppendChild(rec);
XmlElement topupid = xmlDoc.CreateElement("topupid");
topupid.InnerText = grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString();
rec.AppendChild(topupid);
XmlElement amount = xmlDoc.CreateElement("amount");
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
amount.InnerText = txtAmount.Text.Trim();
rec.AppendChild(amount);
XmlElement remarks = xmlDoc.CreateElement("remarks");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
remarks.InnerText = txtRemarks.Text.Trim();
rec.AppendChild(remarks);
}
}
2. Using XMLDataDocument :

DataSet dataSet = new DataSet("root");
DataTable dataTable = new DataTable("rec");
dataTable.Columns.AddRange(new DataColumn[]
{
new DataColumn("topupid"),
new DataColumn("amount"),
new DataColumn("remarks")
});

foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
dataTable.Rows.Add(grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString(),
txtAmount.Text.Trim(),
txtRemarks.Text.Trim());
}
}
dataSet.Tables.Add(dataTable);
XmlDataDocument xmlDataDoc = new XmlDataDocument(dataSet);


XMLDocument is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document.

The XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational DataSet. This class allows components to mix XML and relational views of the underlying data.

Read More..

Friday, October 8, 2010

HANDLING KEYPRESS EVENT OF TEXTBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains textbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield HeaderText="Amount">
<itemtemplate>
<asp:TextBox ID="txtAmount" runat="server" Text='' />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want that user can only enter integer value in txtAmount textbox. I want to handle this client side only. So, I used jquery and handled KeyPress event of textbox. By doing so, user can only enter digits. If user will press any non-numeric key it will not get entered.

<script type="text/javascript">
$(document).ready(function () {
$("#<%=grdTest.ClientID %> INPUT[id$='txtAmount']").keypress(
function IsNumericHandler(e) {
var unicode = e.charCode ? e.charCode : e.keyCode

//if the key isn't the backspace key (which we should allow)
if (unicode != 8) {
//if not a number
if (unicode <> 57)
//disable key press
return false;
}
});
});
</script>

Read More..

Thursday, October 7, 2010

SELECT ALL \ DESELECT FUNCTIONALITY FOR CHECKBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains checkbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield>
<headertemplate>
<asp:checkbox id="ChkAll" runat="server" />
</headertemplate>
<itemtemplate>
<asp:checkbox id="chkRequest" runat="server" />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want on click of ChkAll checkbox (which is in header of grid) all the checkboxes in the first row gets selected. Also, when I deselect any checkbox in first row, ChkAll checkbox gets deselected.

I did this using jquery :

<script type="text/javascript">
$(document).ready(function () {
//To Select/Deselect all checkboxes on click of ChkAll checkbox.
var chkBox = $("input[id$='ChkAll']");
chkBox.click(
function () {
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']")
.attr('checked', chkBox.is(':checked'));
});

// To deselect CheckAll when a GridView CheckBox is unchecked.
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']").click(
function (e) {
if (!$(this)[0].checked) {
chkBox.attr("checked", false);
}
});
});
</script>
Read More..

Tuesday, October 5, 2010

CREATING XML FROM GRIDVIEW AND SAVING IT AS STRING USING XMLDOCUMENT

Today, I came across a requirement in which i have a GridView which have some databound columns and one checkbox cloumn. On a button click, I need to pick all the rows in which checkbox is checked.
I need to convert the data of all the rows in XML format and then at last save it in database. But, before saving it, I again need to convert it to string format.

//These two namespaces are required to create XML Document and String Writer.
using System.Xml;
using System.IO;

protected string CreateXMLFromGrid()
{
// Created new XmlDocument to store Xml.
XmlDocument xmlDoc = new XmlDocument();
//Created the root element and added it to xmlDoc.
XmlElement root = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(root);

foreach (GridViewRow Row in grdTopUpRequest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
XmlElement rec = xmlDoc.CreateElement("rec");
root.AppendChild(rec);

XmlElement topupid = xmlDoc.CreateElement("topupid");
topupid.InnerText = grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString();
rec.AppendChild(topupid);

XmlElement amount = xmlDoc.CreateElement("amount");
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
amount.InnerText = txtAmount.Text.Trim();
rec.AppendChild(amount);

XmlElement remarks = xmlDoc.CreateElement("remarks");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
amount.InnerText = txtRemarks.Text.Trim();
rec.AppendChild(remarks);
}

// Creating an Object of StringWriter and assigining it to XmlTextWriter, whixh will
// copy the xml from xmlDoc to StringWriter.
StringWriter strWriter = new StringWriter();
XmlTextWriter xmlTxtWriter = new XmlTextWriter(strWriter);
xmlDoc.WriteTo(xmlTxtWriter);
return strWriter.ToString();
}
}

Read More..

DIFFERENCE BETWEEN FINDALL() AND WHERE()

First of all how both these works :
Suppose we have a class Person :

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Now, create an object of person class :
Person person = new Person();

Take a List of person class :
List lstPerson = new List();

Now, assign values to this class and add it to list :
person.FirstName = "FirstName1";
person.LastName = "LastName1";
lstPerson.Add(person);

person.FirstName = "FirstName2";
person.LastName = "LastName2";
lstPerson.Add(person);

Now, I want to find all the records where FirstName = "FirstName1".
To do this, I have two options : FindAll() and Where()

FindAll() :
List result = lstPerson.FindAll(delegate(Person per)
{
return per.FirstName == "Firstname1";
});

Where() :
List result = lstPerson.Where((Person per) => per.FirstName == "FirstName1").ToList();


Both will return the same result. So, the question is which one should be used in which situation?
There are some difference between both, now you have to decide which one suits your requirement:

1. FindAll() is a function on the List type, it's not a LINQ extension method like Where. The LINQ extension methods work on any type that implements IEnumerable, whereas FindAll can only be used on List instances (or instances of classes that inherit from it, of course). If our collection is IEnumerable type, then we can't use FindAll() as it's a function of List.

2. The FindAll method of the List class actually constructs a new list object, and adds results to it. The Where extension method for IEnumerable will simply iterate over an existing list and yield an enumeration of the matching results without creating or adding anything (other than the enumerator itself.)

3. Where is much faster than FindAll. No matter how big the list is, Where takes exactly the same amount of time because Where() just creates a query, It doesn't actually do anything, unlike FindAll which does create a list.

Read More..

Monday, October 4, 2010

PRIME NUMBER

public bool IsPrime(int x)
{
if (x == 1)
{
return true;
}
else
{
for (int i = x - 1; i > 1; i--)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
}
Read More..

RECURSIVE PROGRAM TO FIND THE FACTORIAL

public int Factorial(int x)
{
if (x == 1)
{
return x;
}
else
{
return x * Factorial(x - 1);
}
}
Read More..

Saturday, October 2, 2010

CUSTOM CONTROLS IN ASP.NET - GRIDVIEW

In Asp.net, we generally bind GridView with a data source. That data source can be anything like – Data Table, Data View, Class Object, etc. If data source contains some value then it simply binds the grid and displays the records according to grid formatting.
What happens when data source is empty? – GridView will not get displayed.
If suppose, we want to display header and footer of grid in each and every case then what should we do?
One way is to manipulate the data source and add a blank row in it and bind it with grid. It will display the header and footer along with a blank row in grid. This is dirty coding.
Another way is custom controls. Before moving to custom controls first understand the workflow of Grid View.
Steps to create a GridView custom control and use it in aspx page:
1. Take a class and declare a namespace.
2. Inherit your class with GridView (System.Web.UI.WebControls.GridView) class:
using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;

namespace AlwaysShowHeaderFooter {
public class GridViewAlwaysShow : GridView {
}
}
3. Add a delegate above the class:
public delegate IEnumerable MustAddARowHandler(IEnumerable data);

4. Add an event inside the class:
public event MustAddARowHandler MustAddARow;

5. Create a Method to raise this event:
protected IEnumerable OnMustAddARow(IEnumerable data) {
if (MustAddARow == null) {
throw new NullReferenceException("The datasource has no rows. You must handle the \"MustAddARow\" Event.");
}
return MustAddARow(data);
}

6. Now come to main aspx page where you want to display the grid. Register your custom control namespace here:
<%@ Register TagPrefix="Custom" Namespace="AlwaysShowHeaderFooter" %>

7. Add your custom grid on page and call OnMustAddARow function:
OnMustAddARow="grdCustom_MustAddARow"

8. Now define the grdEmail_MustAddARow() in aspx.cs file:
//Flag used to identify if the datasource is empty.
bool _isEmpty = false;

///
/// Handles the MustAddARow event of grdEmail
///

/// The data.
///
protected IEnumerable grdEmail_MustAddARow(IEnumerable data)
{
ListDictionary ldEmails = (ListDictionary)data;
ldEmails.Add("", "");
_isEmpty = true;
return ldEmails;
}
Here we have set a flag _isEmpty = true to check if data source is empty.
I have bind the grid with ListDictionary, you can take any data source.

9. Come back to your custom control class and override the OnDataBound() method to check if data source is empty. As we have added a dummy(blank) row in grdEmail_MustAddARow(), it will display a blank row in grid at runtime which should not come. So we will hide it.
protected override void OnDataBound(EventArgs e)
{

//if in DesignMode, don't do anything special. Just call base and return.
if (DesignMode)
{
base.OnDataBound(e);
return;
}

//hide the dummy row.
if (_isEmpty)
{
Rows[0].Visible = false;
}
base.OnDataBound(e);
}

10. GridView have a method protected internal override void PerformDataBinding(IEnumerable data) which gets called through Databind() method of GridView.

11. Now override the PerformDataBinding method to call OnMustAddARow method if data source is blank. This method gets called from databind() method of GridView.
protected override void PerformDataBinding(IEnumerable data)
{

//If in DesignMode, don't do anything special. Just call base and return.
if (DesignMode)
{
base.PerformDataBinding(data);
return;
}

//Count the data items.(I wish I knew a better way to do this.)
int objectItemCount = 0;
foreach (object o in data)
{
objectItemCount++;
}

//If there is a count, don't do anything special. Just call base and return.
if (objectItemCount > 0)
{
base.PerformDataBinding(data);
return;
}

//Set these values so the GridView knows what's up.
SelectArguments.TotalRowCount++;
_isEmpty = true;

//If it's a DataView, it will work without having to handle the MustAddARow event.
if (data.GetType() == typeof(DataView))
{
//Add a row and use that new view.
DataView dv = (DataView)data;
dv.Table.Rows.InsertAt(dv.Table.NewRow(), 0);
base.PerformDataBinding(dv.Table.DefaultView);
return;
}
else
{
//If you are using some custom object, you need to handle this event.
base.PerformDataBinding(OnMustAddARow(data));
return;
}
}

That’s it!! Your custom control is ready to run...:)
Read More..

WORKFLOW OF GRIDVIEW

Have you ever thought how grid view handles all the events like RowDataBound, RowCommand, RowDeleting, RowUpdating, etc...? If you look in System.Web.UI.WebControls.GridView class, you will find lots of properties, events and methods.

Let’s take RowDataBound as an example to understand the GridView workflow.
1. We have an event RowDataBound which gets fired OnRowDataBound method :
// Summary: Occurs when a data row is bound to data in a
System.Web.UI.WebControls.GridView control.
public event GridViewRowEventHandler RowDataBound;

2. We have a delegate to handle RowDataBound event :
using System;
namespace System.Web.UI.WebControls
{
// Summary: Represents the method that handles the
// System.Web.UI.WebControls.GridView.RowCreated and S
// System.Web.UI.WebControls.GridView.RowDataBound events of a
// System.Web.UI.WebControls.GridView control.
// Parameters:
// sender: The source of the event.
//e: A System.Web.UI.WebControls.GridViewRowEventArgs object that contains the event data.
public delegate void GridViewRowEventHandler(object sender, GridViewRowEventArgs e);
}

3. We have a method OnRowDataBound() which raises the RowDataBound event :
// Summary: Raises the System.Web.UI.WebControls.GridView.RowDataBound event.
// Parameters:
// e: A System.Web.UI.WebControls.GridViewRowEventArgs that contains event data.
protected virtual void OnRowDataBound(GridViewRowEventArgs e);

4. Create grdTest_RowDataBound function in aspx.cs and write the code which you want to execute for each row when data binding takes and call it in OnRowDataBound()
Here I am generating the Serial No., which will be displayed in grid.

private int intSerialNo = 1;

/// Handles the RowDataBound event of the grdEmail control.
/// The source of the event.
/// The instance containing the event data.
protected void grdEmail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow) || (e.Row.RowType == DataControlRowType.Footer))
{
Label serialNumber = (Label)e.Row.FindControl("lblSno");
serialNumber.Text = intSerialNo.ToString() + ".";
intSerialNo = intSerialNo + 1;
}
}

This is how GridView works!!
Read More..