Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, September 8, 2010

Numeric textbox javascript...

    <input type='text' onkeydown='text_keydown(event)' />

<script language='javascript' type='text/javascript'>
function text_keydown(e)
{
var key;
document.all ? key = e.keyCode /*IE*/ : key = e.which /*FF*/;
if(!(key > 47 && key < 58) && key != 8 && key != 37 && key != 39 && key != 16 && key != 46)
{
cancelevent(e);
}
}

function cancelevent(e)
{
if(window.event) // IE
{
window.event.returnValue = false;
}
else // FF
{
e.preventDefault();
}
}
</script>

Sunday, September 5, 2010

Evolution of data query in C#...

One of the most common operation in programming is data query. In C# 1.2, normally I would use a custom collection class that derived from System.Collections. But for sake of example here, I'll show it with an ArrayList instead.

Here's a class that'll become an element of the collection (yes, I know Auto-Implemented Properties).
    public class Student
{
private int _id;
private string _name;
private string _gender;

public Student()
{
}

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

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

public string Gender
{
get { return _gender; }
set { _gender = value; }
}
}
This is how I normally code in C# 1.2 (.NET Framework 1.1) with an ArrayList.
    private ArrayList SomeFilterMethod(ArrayList myList)
{
ArrayList result = new ArrayList();

for (int x = 0; x < myList.Count; x++)
{
if (((Student)myList[x]).Gender == "Male")
{
result.Add(myList[x]);
}
}

return result;
}
Generic list with action and predicate was introduced in C# 2.0 (.NET Framework 2.0). This is how my code will look like.
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return mylist.FindAll(GetMaleStudents);
}

private bool GetMaleStudents(Student item)
{
return item.Gender == "Male";
}
Not to forget an anonymous methods.
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return mylist.FindAll( delegate(Student item) { return item.Gender == "Male"; } );
}
In C# 3.0 (.NET Framework 3.5), there's LINQ with 2 flavours.
1) Lambda Expression
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return mylist.FindAll( item => item.Gender == "Male" );
}
2) Query Expression
    private List<Student> SomeFilterMethod(List<Student> myList)
{
return (from student in mylist
where student.Gender == "Male"
select student).ToList<Student>();
}
Between the two, personally I prefer the former.