Deleting value in a databound DataGridViewTextBoxColumn sets bound member to 'Nothing'Deleting value in a databound DataGridViewTextBoxColumn sets bound member to 'Nothing'
Old forum URL: forums.lhotka.net/forums/t/1330.aspx
stefan posted on Tuesday, September 26, 2006
Hi,
I have bound a child collection (BusinessListBase) to a DataGridView-control, allowing inline-editing.
I get a SqlException when I try to edit a string member of one child inside the datagrid. Selecting the field and pressing 'Del' or reducing the string length using the backspace key have the same effect: Databinding sets the bound object-member to 'Nothing', instead of setting it to a 'zerolength-string', as I would expect (and as 'normal' textboxes do). My stored procedure then cannot handle this, as it expects an non-null parameter.
I'm feeling a little stupid asking this, as I am just using a standard databinding approach.
(It must be simple!)
Do I really need to step into CellValidating?
Any hint would be greatly appreciated!
Stefan
rgreen replied on Monday, October 02, 2006
Do you have code in your setter to handle null values? The following code sample comes from Lhotka's CSLA sample application in the project.cs file.
public string Name
{
...
(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_name != value)
{
_name = value;
PropertyHasChanged();
}
}
}
ajj3085 replied on Monday, October 02, 2006
rgreen: if (value == null) value = string.Empty;
This can be simplified a bit in .Net 2.0.
value ?? ""; // is equivolent to if (value == null) value = string.Empty;
HTH
Andy
Mark replied on Monday, October 02, 2006
It would actually be...
value = value ?? String.Empty; // or "", whichever you prefer
I'm not sure I'd be in favor of the above code, though, because it will always result in a new string being assigned to "value", even when it's not necessary. Since strings are immutable, you'll end up with a little extra memory usage as the new string is allocated and the old string is disposed of. You're probably not talking about a lot of extra memory usage with this code, but thought I'd mention it.
For what it's worth...
ajj3085 replied on Tuesday, October 03, 2006
Ya, forgot the assignment part.
Its true that strings are immutable, but we aren't changing the string, we are doing a reference assignment.
Try this in a console application.
string x, y;
x = " My string";
y = x;
Console.WriteLine( object.ReferenceEquals( x, y ) );
Console.ReadLine();
Copyright (c) Marimer LLC