Thursday, August 27, 2009

Use header checkbox in GridView in ASP.NET

Here I am going to give you a very easy steps to use the checkbox in the header of the Gridview in ASP.NET.




Steps:
1. I have created a class “Customer” and fill the gridview with the collection of customers.


public class Customer

{

int id;
string name;
string city;

public string City
{
get { return city; }
set { city = value; }
}

public string Name
{
get { return name; }
set { name = value; }
}

public int Id
{
get { return id; }
set { id = value; }
}

public Customer(int customerID, string customerName, string customerCity)
{

id = customerID;
name = customerName;
city = customerCity;
}

}


2.Created a gridview in the default.aspx page


<asp:GridView ID="dgridCustomer" runat="server" AutoGenerateColumns="false" Width="592px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
 
<input type="checkbox" class="chkHeader" id="HeaderCheckBox" onclick="javascript:Check(this)" name="ItemCheckBox" runat="Server" />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" value='<%# DataBinder.Eval(Container.DataItem, "Id") %>' class="chkItem"
id="ItemCheckBox" name="ItemCheckBox" runat="Server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "City") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>



3.To fill the gridview following functions has been used in default.aspx.cs file

protected void Page_Load(object sender, EventArgs e)

{

lblMsg.Visible = false;

if (IsPostBack) return;

FillCustomer();

}

private void FillCustomer()
{
List obCustomers = new List();

obCustomers = GetAllCustomers();

Session["Customers"] = obCustomers;

dgridCustomer.DataSource = obCustomers;
dgridCustomer.DataBind();
}

private List GetAllCustomers()
{
List obCustomers = new List();

Customer obCustomer = new Customer(1, "name1", "city1");
obCustomers.Add(obCustomer);

obCustomer = new Customer(2, "name2", "city2");
obCustomers.Add(obCustomer);

obCustomer = new Customer(3, "name3", "city3");
obCustomers.Add(obCustomer);

obCustomer = new Customer(4, "name4", "city4");
obCustomers.Add(obCustomer);

obCustomer = new Customer(5, "name5", "city5");
obCustomers.Add(obCustomer);

return obCustomers;

}



4.When header checkbox of the gridview is clicked then all the item checkboxes should be checked and if header checkbox is unchecked then all the item checkboxes should be unchecked. To do this I have created a javascript function and added in the default.aspx page.

 function Check(varchk)

{

var objInputs = document.getElementsByTagName('input')
for(i=0;i {
if(varchk.checked)
{
if(objInputs[i].className==='chkItem')
{
objInputs[i].checked=true;
}
}
else
{
if(objInputs[i].className==='chkItem')
{
objInputs[i].checked=false;
}
}
}
}


5.Remove all the checked record from the gridview, the following method has been used
in the Remove button.

 protected void btnRemove_Click(object sender, EventArgs e)

{
List obCollection = (List)Session["Customers"];

foreach (GridViewRow row in dgridCustomer.Rows)
{
System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)dgridCustomer.Rows[row.RowIndex].FindControl("ItemCheckBox");

if (chk.Checked)
{
Customer obCustomer = obCollection.Find(delegate(Customer obj) { return obj.Id == Convert.ToInt32(chk.Value); });

obCollection.Remove(obCustomer);

lblMsg.Visible = true;

lblMsg.Text = "Customer information deleted successfully.";
}
}

dgridCustomer.DataSource = obCollection;
dgridCustomer.DataBind();

}



Below method is used to find the checked item from the collection.

Customer obCustomer = obCollection.Find(delegate(Customer obj) { return obj.Id == Convert.ToInt32(chk.Value); });




Download :



Saturday, August 1, 2009

Decorator Pattern

There are numbers of way we used in the designing software application. These ways are called Patterns, and in the object-oriented programming, we use so many patterns. Decorator Pattern is a design pattern in the object-oriented programming that allows us to add the new functionality in the existing class dynamically. To understand let me give you a simple example. Suppose you have an application in ASP.NET and SQL Server.
In your business logic, you have written all you logics. i.e.

1. Insert()
2. Update()
3. Delete
4. Get()

In these logics, you have written the code according to your SQL Server fetching technique. You have used System.Data.SqlClient and open/close the connection with SQL Server and done all the insert/update/delete opertaions with SQL Server. You have also called this business logic objects into your UI layer. Now your application is fully dependent in SQL Server. The problem start now, you have a single application where you have done your all effort with the SQL Server and the new requirement is you have to also provide the support of the Microsoft Access with the same database and UI. Then what will you do? You have to create the another business logic with the Microsoft Access as well as have to change all the logic of UI layer because it is accessing the SQL Server business layer logic right now. It will force you rethink again in your design pattern. In such type of situation Decorator Pattern help you to get up. Let me make it simpler. Suppose, I have an asp.net .aspx page where I have to show all products information. Remember we have two databases one is in SQL Server, another is in Microsoft Access, and we have to write the code in a single UI. At the run time, we can decide which database we have to use. First, I will create an interface IProduct. (Here I am using a console application.)

public interface IProduct
{
bool Insert(int id, string name);
bool Update(int id, string name);
bool Delete(int id);
string GetRecords();
}

Then I have to create a Product class which will contains all the operations with SQL Server database. This Product class will inherits the IProduct interface.


public class ProductSQLServer : IProduct 
{
int id = 10;
string name = "SQL Server";

#region IProduct Members

public bool Insert(int id, string name)
{

//insert logic

return true;

}

public bool Update(int id, string name)
{
//upate logic
return true;
}

public bool Delete(int id)
{
//delete login
return true;
}

public string GetRecords()
{
return "sql server : id=" + id + " name=" + name ;
}

#endregion

}


public class ProductMicrosoftAccess : IProduct
{
int id = 10;
string name = "MicrosoftAccess";

#region IProduct Members

public bool Insert(int id, string name)
{
//insert into the microsoft access
return true;
}

public bool Update(int id, string name)
{
//update in the microsoft access
return true;
}

public bool Delete(int id)
{
//delete from the microsoft access
return true;
}

public string GetRecords()
{
return "MicrosoftAccess : id=" + id + " name=" + name ;
}

#endregion
}


Now in the UI layer we can decide in the run time what type of object (SQL Server/Access) need to be accessed.

In the view product.aspx page I can decide whether I want to create the object of ProductMicrosoftAccess class or ProductSQLServer class.
For that you have to use the IProduct interface


static void Main(string[] args)
{
IProduct  obOperation = new ProductMicrosoftAccess();

Console.WriteLine(obOperation.GetRecords());

obOperation = new ProductSQLServer();

Console.WriteLine(obOperation.GetRecords());


Console.ReadLine();
}


You can choose the type of database by setting the key in your web.config file or any configuration file.




Download :