Wednesday, May 21, 2008

Convertion between Double & DateTime using C#

Double to DateTime
// convert Double to DateTime
double d = 38670.333333333336;
// dt is now a .NET date time
// convert DateTime
DateTime dt = DateTime.FromOADate(d);
this.textBox1.Text = String.Format("{0:MMM dd, yyyy HH:mm}", dt);

DateTime to Double
// convert DateTime to Double
string st = "2006-12-12";
// dt is now a .NET date time
DateTime dt = DateTime.Parse(st.ToString());
// convert double
double d = Convert.ToDouble(dt.ToOADate());
this.textBox1.Text = d.ToString();

Event-Delegate using C# to communicate between UserControl & Form

There are lots of ways to use Delegate in C#. Shown below only 2 ways of how to use Delegate to communicate between UserControl & Form.

1. Using Event-Delegate:
Inside UserControl the code will be like below:
// using event - delegate
public delegate void MyDelegate(string str);
public event MyDelegate MyEvent;

private void button1_Click(object sender, EventArgs e)
{
// event that will be fire from usercontrol & catch by form
MyEvent("SAJAL");
}

Inside Form the code will be like below:
// attach method to fire
this.userControl11.MyEvent += new UserControl1.MyDelegate(MyMethod);

void MyMethod(string str)
{
this.textBox1.Text = str;
}

2. Using Delegate:
Inside UserControl the code will be like below:
// using only delegate
public delegate void MyDelegate(string str);
public MyDelegate NewMyDelegate;

// need to store the delegate
public void FireMe(MyDelegate md)
{
NewMyDelegate = md;
}

private void button1_Click(object sender, EventArgs e)
{
NewMyDelegate("BAPPY");
}

Inside Form the code will be like below:
// attach method to fire
this.userControl11.FireMe(new UserControl1.MyDelegate(MyMethod));

void MyMethod(string str)
{
this.textBox1.Text = str;
}

The basic difference is to use an extra method for Number 2.