Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Dynamic value for new row in DataGrid
Message
From
27/12/2006 10:28:20
 
 
To
26/12/2006 09:05:55
General information
Forum:
ASP.NET
Category:
ADO.NET
Environment versions
Environment:
C# 1.1
Miscellaneous
Thread ID:
01180182
Message ID:
01180488
Views:
15
This message has been marked as the solution to the initial question of the thread.
Andrus,

Two things to change in your code.

1) Check for DBNull.Value, not null
2) Use the TableNewRow event, not the RowChanging event
table.TableNewRow += new DataTableNewRowEventHandler(table_TableNewRow);
void table_TableNewRow(object sender, DataTableNewRowEventArgs e)
{
	string pk = e.Row.Table.PrimaryKey[0].ColumnName;
	if (e.Row[pk] == DBNull.Value)
		e.Row[pk] = new System.Guid();
}
See if that will work for you.

~~Bonnie



>I have .NET 1 WinForms dataGrid bound to dataTable.
>dataTable has primary key field.
>dataTable constraints should be checked during editing.
>
>If user moves out from new row, an error occurs.
>RowChanging event does not fire before error.
>
>How to fill field with dynamic default value when new row is added to DataGrid ?
>
>To reproduce:
>
>1. Run code
>2. Enter data to first column only
>3. Press Down Arrow
>
>Observed error:
>
>---------------------------
>Committing the row to the original data store has caused an error.
>---------------------------
>Value Column 'Column2' does not allow nulls. Do you want to correct this value?
>
>Expected:
>
>No error. Primary key column should be filled.
>
>
using System.Windows.Forms;
>using System.Data;
>static class Program {
>	static void Main() {
>		Application.Run(new Frm());
>		}
>	}
>
>class Frm: Form {
>	public Frm() {
>		DataTable table = new DataTable();
>		DataColumn[] keys = new DataColumn[1];
>		DataColumn column1 = new DataColumn();
>		DataColumn column2 = new DataColumn();
>		DataGrid grid = new DataGrid();
>		
>		grid.Dock = DockStyle.Fill;
>		table.Columns.Add(column1);
>		table.Columns.Add(column2);
>		keys[0] = column2;
>		table.PrimaryKey = keys;
>		Controls.Add(grid);
>		table.RowChanging += new DataRowChangeEventHandler(OnRowChanging);
>		grid.SetDataBinding(table, "");
>		}
>
>	private void OnRowChanging(object sender, DataRowChangeEventArgs e) {
>		if (e.Action == DataRowAction.Add) {
>			string pk = e.Row.Table.PrimaryKey[0].ColumnName;
>			if (e.Row[pk] == null)
>				e.Row[pk] = new System.Guid();
>			}
>		}
>	}
>
Bonnie Berent DeWitt
NET/C# MVP since 2003

http://geek-goddess-bonnie.blogspot.com
Previous
Reply
Map
View

Click here to load this message in the networking platform