DBnull and checkBox when adding new record

P

PeterZ

Yo,

Got a checkbox which I databind at runtime to a numeric column. It works
fine but when I add a new record I get the error:

--------------------------------
An unhandled exception of type 'System.InvalidCastException' occurred in
mscorlib.dll

Additional information: Object cannot be cast from DBNull to other types.
--------------------------------

I'm databinding just after adding a new record, so the order of events is:

1. Add new record code:
private void AddRecord()
{
// daBuilding is my DataAdapter, dsBuilding is my DataSet.
daBuilding.FillSchema(dsBuilding, System.Data.SchemaType.Source,
"BUILDING");

this.BindingContext[dsBuilding, "BUILDING"].AddNew();
this.DataBindControls();
}

2. Databinding code:
private void DataBindControls()
{
// Check the global flag to see if we have already databound controls.
if (this.dataBound)
return;
 
C

Cowboy

This is one area where strongly typed datasets save you a lot of time. In a
strongly typed dataset, you can check for a null.

if(!ds.MyTable.IsCheckBox1Null)
{
}

Overall, a field that links to a checkbox should always have a 0 or a 1 (bit
field in SQL Server). If you are allowing nulls, you are defeating the idea
of setting up a Boolean control (checkbox can either be checked or not, and
not in some "unknown" state, which is what Null represents). If you ask the
question Do you want our email letter? The answer is either yes or no, not
NULL.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
 
P

PeterZ

I understand what you're saying, but what happens when you create a
new row in your table? All values on the new row are null, are they
not? Only after the user fills in the necessary information thorugh
the form will there be actual values.

Databinding through code is certainly a pain!
 
M

mhnd

Hi,
i think the prolem is in the dataset as i figured out
you have to set a default value for the boolean column
Example:
dataSet1.Tables[0].Columns[2].DefaultValue = true; // or false
as u wish

this code must be added before the addnew() method

regards,
Mouhannad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top