I have a winforms application with a numeric field on a form. This starts out null then if I set it to a number, change focus then clear again the textbox changes back to the number previously entered. If I change the number eg. from 4 to 5 it is updated correctly but I want the user to be able to clear what has been entered.
Here is some sample code that demonstrates this behaviour:
public partial class Form1 : Form
{
DataTable table = new DataTable("TableName");
public Form1()
{
DataColumn column = new DataColumn("NumericColumnName", typeof(Double));
column.AllowDBNull = true;
table.Columns.Add(column);
object[] rowData = new object[1];
rowData[0] = DBNull.Value;
table.Rows.Add(rowData);
InitializeComponent();
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = table;
Binding binding = new Binding("Text"开发者_开发知识库, bindingSource, "NumericColumnName");
textBox1.DataBindings.Add(binding);
}
}
This is in a brand new .net 3.5 forms project in Visual Studio 2008. I added two textboxes to the form.
My actual application generates the dataset differently however it has the same behaviour. Do bindings to numeric columns of a datatable allow nulls.
In fact You can allow NULL values, however You have to add additional parsing to the code:
binding.Parse += new ConvertEventHandler(ParseNumeric);
where ParseNumeric has the following form:
private void ParseNumeric(object sender, ConvertEventArgs e)
{
if(e.Value.Equals(""))
e.Value = DBNull.Value;
}
for me this code allows empty texts in text boxes which are then represented by NULL values in database.
By default double is a non-nullable field. So even if you put a null in it will change to 0.
You need to change the column datatype to be double?. double? is a nullable type.
UPDATE
Upon further looking, typed datasets do not support nullable types.
A solution is to use a 'loose' type (IE: object) but then you will have to check it to make sure the input is valid.
I tested with your sample and change it to object allowed me to empty the box.
精彩评论