ammar ammar - 7 months ago 36
C# Question

Int field in Winform does not update null values in SQL Server database using C#

In my Winforms C# application, I have fields with

data type and they are set to accept null values in SQL Server database (allow nulls).

In the forms I have some textboxes which are bound to those int data type fields. If I don't enter anything while creating a new record, it accepts. If I enter a number in the textbox, it also accepts it, and then if I delete it, it doesn’t accept it anymore and even doesn't allow me to move to the next field.

If I set its value as null or
through code, it simply ignores and does not even update changes which I made in other non int text fields.

I am using following method to update.


What can I do for the textbox to accept null values?

I have tried following.

IDTextBox.Text = "";
IDTextBox.Text = null;


This seems to be one of the WF data binding bugs. I can't say what exactly is causing it, but in order to make it work one should set Binding.NullValue property to "" (empty string, the default is null).

I couldn't find a way to do that in the designer, and also it would be quite annoying to locate all text boxes needed. So I would suggest you the following quick-and-dirty approach. Create a helper method like this:

public static class ControlExtensions
    public static void FixTextBoxBindings(this Control control)
        if (control is TextBox)
            foreach (Binding binding in control.DataBindings)
                if (binding.NullValue == null) binding.NullValue = "";
        foreach (Control child in control.Controls)

and then simply include the following in your form Load event: