U¿ytkownik "Aart Hoevenberg said:
Hi Miha,
Both events (changing and changed) fire when changing a column in code.
What happens between those events? What could be a good usage for placing
code in the changing event or the changed event?
Thanks
If you throw exception in changing event you can retire changes. Changed
events you can use to make changes in other tables but you can't (in simple
way) resign.
For example:
using System;
using System.Data;
namespace chngDtEvent
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
test myT = new test();
myT.AddSomeData();
myT.ListPersons();
System.Console.ReadLine();
}
}
public class test
{
private DataTable myDt = new DataTable("myT");
public test()
{
//column definition
DataColumn dc = new DataColumn("Name",
System.Type.GetType("System.String"));
myDt.Columns.Add(dc);
//events definitions
myDt.RowChanging +=
new DataRowChangeEventHandler(myDt_RowChanging);
myDt.RowChanged +=
new DataRowChangeEventHandler(myDt_RowChanged);
}
public void AddSomeData()
{
AddOnePerson("Ben");
AddOnePerson("Bill");
AddOnePerson("George");
}
public void AddOnePerson(string name)
{
try
{
DataRow myDr = myDt.NewRow();
myDr["Name"] = name;
myDt.Rows.Add(myDr);
}
catch(Exception ex)
{
System.Console.WriteLine("Error: " + ex.Message);
}
}
public void ListPersons()
{
System.Console.WriteLine("\nEnlisted person:");
foreach(DataRow dr in myDt.Rows)
System.Console.WriteLine(dr["Name"].ToString());
}
private void myDt_RowChanging(object sender, DataRowChangeEventArgs e)
{
if(e.Row["Name"].ToString() == "Bill")
throw new Exception("Bill can not be added here");
}
private void myDt_RowChanged(object sender, DataRowChangeEventArgs e)
{
if(e.Row["Name"].ToString() == "Ben")
System.Console.WriteLine("Warring! Ben was added!");
}
}
}
Regards,
Grzegorz