DataTable的事件
DataTable 对象提供一系列可以由应用程序处理的事件
名称 |
说明 |
ColumnChanged |
在 DataRow 中指定的 DataColumn 的值被更改后发生。 |
ColumnChanging |
在 DataRow 中指定的 DataColumn 的值发生更改时发生。 |
RowChanged |
在成功更改 DataRow 之后发生。 |
RowChanging |
在 DataRow 正在更改时发生。 |
RowDeleted |
在表中的行已被删除后发生。 |
RowDeleting |
在表中的行要被删除之前发生。 |
TableCleared |
清除 DataTable 后发生。 |
TableClearing |
清除 DataTable 后发生。 |
TableNewRow |
插入新 DataRow 时发生。 |
示例:
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(new object[] { 1, "张三" });
dt.ColumnChanged += new DataColumnChangeEventHandler(dt_ColumnChanged);
dt.ColumnChanging += new DataColumnChangeEventHandler(dt_ColumnChanging);
dt.RowChanged += new DataRowChangeEventHandler(dt_RowChanged);
dt.RowChanging += new DataRowChangeEventHandler(dt_RowChanging);
dt.Rows[0]["Name"] = "李四";
Console.ReadKey();
}
static void dt_RowChanging(object sender, DataRowChangeEventArgs e)
{
if (e.Action != DataRowAction.Nothing)
{
Console.WriteLine("RowChanging:Action = " + e.Action + ",Name=" + e.Row["Name"]);
}
}
static void dt_RowChanged(object sender, DataRowChangeEventArgs e)
{
if (e.Action != DataRowAction.Nothing)
{
Console.WriteLine("RowChanged:Action = " + e.Action + ",Name=" + e.Row["Name"]);
}
}
static void dt_ColumnChanging(object sender, DataColumnChangeEventArgs e)
{
Console.Write("ColumnChanging:");
Console.Write(e.Column.ColumnName + " equals '" + e.Row[e.Column] + "',changing to'" + e.ProposedValue + "'\n");
}
static void dt_ColumnChanged(object sender, DataColumnChangeEventArgs e)
{
Console.Write("ColumnChanged:");
Console.Write(e.Column.ColumnName + " changed to " + e.ProposedValue + "\n");
}
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(new object[] { 1, "张三" });
dt.ColumnChanged += new DataColumnChangeEventHandler(dt_ColumnChanged);
dt.ColumnChanging += new DataColumnChangeEventHandler(dt_ColumnChanging);
dt.RowChanged += new DataRowChangeEventHandler(dt_RowChanged);
dt.RowChanging += new DataRowChangeEventHandler(dt_RowChanging);
dt.Rows[0]["Name"] = "李四";
Console.ReadKey();
}
static void dt_RowChanging(object sender, DataRowChangeEventArgs e)
{
if (e.Action != DataRowAction.Nothing)
{
Console.WriteLine("RowChanging:Action = " + e.Action + ",Name=" + e.Row["Name"]);
}
}
static void dt_RowChanged(object sender, DataRowChangeEventArgs e)
{
if (e.Action != DataRowAction.Nothing)
{
Console.WriteLine("RowChanged:Action = " + e.Action + ",Name=" + e.Row["Name"]);
}
}
static void dt_ColumnChanging(object sender, DataColumnChangeEventArgs e)
{
Console.Write("ColumnChanging:");
Console.Write(e.Column.ColumnName + " equals '" + e.Row[e.Column] + "',changing to'" + e.ProposedValue + "'\n");
}
static void dt_ColumnChanged(object sender, DataColumnChangeEventArgs e)
{
Console.Write("ColumnChanged:");
Console.Write(e.Column.ColumnName + " changed to " + e.ProposedValue + "\n");
}