Friday, 24 July 2009

How to highlight a GridView's row on mouse hover in ASP.net?

With small amount of JavaScript we can correctly highlight the GridView row when user hovers over each row. This can be very helpful when we have a very wide report. To achieve this, we can use the technique I discussed in the previous article: Calling a JavaScript function from server side code.

The following JavaScript can do the trick, please note this also works well if you have set the AlternatingRowStyle of the GridView.

function highlight(tableRow, active) {
if (active) {
tableRow.originalstyle = tableRow.style.backgroundColor;
tableRow.style.backgroundColor = '#cfc';
}
else {
tableRow.style.backgroundColor = tableRow.originalstyle;
}
}

Now we can drag a GridView to the page and selected a valid data source. In this demo, I use the Order table in Northwind database. In order to highlight the row on mouse hover, we need to add some custom JavaScript code to onmouseover and onmouseout event handlers of the rows of our GridView. In codehind we have:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onmouseover"] = "highlight(this, true);this.style.cursor = 'pointer'";
e.Row.Attributes["onmouseout"] = "highlight(this, false);";
}

Run the application, you will see the result as the screenshot below:

How to call a Server Side Function from Client Side Code using JavaScript in ASP.net Ajax

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX. ASP.Net AJAX introduced a technique called PageMethods using which we can call server side methods from JavaScript. Try to imagine a scenario, in a user registration form, when user type a user name in a textbox, a server side process is triggered to find whether this is an exiting user or not in our user table in the database. In this example I am using the SQL Server 2005 as backend.

1.Create a demo table on Northwind db and insert 3 users into the table.

CREATE TABLE demo(user_id varchar(10) PRIMARY KEY);
insert into demo values ('user1');
insert into demo values ('user2');
insert into demo values ('user3');

2.Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag. Let’s create a simple function as below:

[System.Web.Services.WebMethod]
public static bool IsUserExist(string strUserID)
{
bool blUserExist = false;
string connectionString = "Data Source=localhost;Initial Catalog=Northwind; " +
"Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string strSqlStatement = "select * from demo where user_id = '" + strUserID + "'";
SqlCommand cmd = new SqlCommand(strSqlStatement, conn);
SqlDataReader reader = cmd.ExecuteReader();

if (reader.HasRows)
blUserExist = true;

reader.Close();
conn.Close();

return blUserExist;
}

3. Go to the Markup page and drag a ScriptManager to the page. The “EnablePageMethods” attribute has to be added on the ScriptManager tag and set it to “true”.




4. Adding a simple HTML TextBox as:



5. Adding the JavaScript code as below:



The “OnSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnFailure” will be called if an exception is thrown.

6. Running the application. Will see the screenshot as below:

Tuesday, 21 July 2009

Ways to call JavaScript function from C# in ASP.net

As we all know in ASP.net framework, C# code executes on the server whereas JavaScript code executes in the client's browser. We can't actually "access" JavaScript from the server-side. All that we can do is write the JavaScript function call into the markup and have it execute when all server-side processing is completed and the page renders to the browser.

There are number of workarounds we can achieve this. To demonstrate let us declare a JavaScript Function in the markup page first.



Now we need to decide how we are going to execute this function in our code page.

1. We want to call the function on a page_load event, then we can put the code below to the page_load method:

protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "alertMe();", true);
}
}

2. We want to call the function on a buttion click event, we can write the code as:

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick", "alertMe()");
}

Or

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes["onclick"] = "alertMe()";
}

3. If we have a GridView and we want to call the method when the GridView Row get clicked by the user. This can be very useful in master-detail relationship data. For example, we have a summary GridView report shows customer order headers, when user click on the row, a small window will popup to show the details of the selected order. To do this, we simply add the following line to the GridView RowDataBound event:

GridView1.Attributes["onclick"] = "alertMe()";

OOP Basics: Inheritance

This little article is a basic introduction of using inheritance in C#. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective employment of reuse, you can save time in your programming. Let's take a look at the program below:

using System;

namespace InheritanceSample
{
public class Parent
{

string parentString;
public Parent()
{
Console.WriteLine("Parent Constructor.");
}

public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}

public void print()
{
Console.WriteLine("I'm a Parent Class.");
}

}

public class Child : Parent
{

public Child(): base("From Parent")
{
Console.WriteLine("Child Constructor.");
}

public new void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}

public static void Main()
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
}

Output:


Base classes are automatically instantiated before derived classes. Notice the output from above: The Parent constructor executed before the Child constructor. When a base class declares a method as virtual, a derived class can override the method with its own implementation. If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class.

A derived class can hide base class members by declaring members with the same name and signature. The new modifier can be used to explicitly indicate that the member is not intended to be an override of the base member. The use of new is not required, but a compiler warning will be generated if new is not used

Friday, 5 June 2009

OOP Basic: Polymorphism

Polymorphism gives us the ultimate flexibility in extensibility which is a basis of OO programming. Understanding Polymorphism is crucial to any OO language professional. The benefit of polymorphism is that you don’t need to know the object’s class to execute the polymorphic behaviour. We use polymorphism to achieve the late binding. For example, you may have many classes in an application, each with its own save method. When the application is saved, each object knows the class it belongs to and automatically calls the correct save method.

using System;

namespace Polymorphism
{
class Shape
{
public virtual void draw()
{
Console.WriteLine("Draw shape....");
}
}

class Circle: Shape
{
public override void draw()
{
Console.WriteLine("Draw circle....");
}
}

class Triangle : Shape
{
public override void draw()
{
Console.WriteLine("Draw triangle....");
}
}

class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("Draw rectangle...");
}
}

class Create
{
public Shape CreateShape(string str)
{
Shape s;
switch (str)
{
case "c":
s = new Circle();
break;
case "r":
s = new Rectangle();
break;
case "t":
s = new Triangle();
break;
default:
s = new Shape();
break;
}
return s;
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please type a Shape class you want to create: ");
string strShape = Console.ReadLine();
Console.WriteLine("string is: {0}", strShape);

Create c = new Create();
Shape s = c.CreateShape(strShape);
s.draw();
Console.ReadLine();
}
}
}

In the above example, if we want to add a new class to draw Oval shape, we will have a class like:

class Oval: Shape
{
public override void draw()
{
Console.WriteLine("Draw oval....");
}
}

We want to be able to ‘plug-in’ this class into our application without having to make any code changes in the original code and call the draw() of Oval class during run time. By using Polymorphism, the only place we need to make the change is our Create method and we leave our client application code untouched.

Understanding polymorphism is key to designing scalable, plug-and-play architecture application.

Monday, 1 June 2009

Copying a DataGridViewRow to another DataGridView Control

Sometimes a simple task can be very tricky. Today I was trying to make a copy of DataGridView to another DataGridView, in the traget DataGridView I need to delete a few rows and possibly add a few new DataGridViewColumn(s), all these changes must have no impact whatsoever on the Original DataGridView object. Because of the nature of C#, object is passed by reference. So I cannot do things like DataGridView dgv_copy = dgv_original if I want to make some changes in the second DataGridView without affecting the original one.

What should I do? Firstly I need to create columns first, populate the DataGridViewColumns from the original to the new one. This is very straight forward, however when it comes to copy the rows. I came across a problem. The DataGridViewRow clone method does not work as expected. The Clone method copies the row and its property values, but does NOT copy the cell values that the row contains. So we have to write some code to copy the cell values. Please find the working example below and feel free to let me know should you have any queries.

private DataGridView CopyDataGridView(DataGridView dgv_org)
{
DataGridView dgv_copy = new DataGridView();
try
{
if (dgv_copy.Columns.Count == 0)
{
foreach (DataGridViewColumn dgvc in dgv_org.Columns)
{
dgv_copy.Columns.Add(dgvc.Clone() as DataGridViewColumn);
}
}

DataGridViewRow row = new DataGridViewRow();

for (int i = 0; i < dgv_org.Rows.Count; i++)
{
row = (DataGridViewRow)dgv_org.Rows[i].Clone();
int intColIndex = 0;
foreach (DataGridViewCell cell in dgv_org.Rows[i].Cells)
{
row.Cells[intColIndex].Value = cell.Value;
intColIndex++;
}
dgv_copy.Rows.Add(row);
}
dgv_copy.AllowUserToAddRows = false;
dgv_copy.Refresh();

}
catch (Exception ex)
{
cf.ShowExceptionErrorMsg("Copy DataGridViw", ex);
}
return dgv_copy;
}

Dynamically display tooltips when mouse hover a DataGridViewCell in WinForm application

In one of my recent projects, a customer asked me to provide a dynamic tool tip depending on the DataGridViewCell that user have his mouse hovered. For a Windows Forms DataGridView, you can handle the dataGridView1.CellToolTipTextNeeded event and dynamically provide the tip text there.

dataGridView1.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(data GridView1_CellToolTipTextNeeded);
void dataGridView1_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = string.Format("tip for row {0}, col {1}", e.RowIndex, e.ColumnIndex);
}

Run the application, you would see a similar screen shot as below: