Check all fields for DBNull at once?

liquidspaces

Well-known member
Joined
Nov 19, 2002
Messages
74
Location
Richmond, VA
I have a form that has maybe 50 fields. The user can search for specific data, though not all of the data is required in the database. Because of that, there will be some null values in some of the fields. If I dont check for DBNULL, the program crashes when I try to place the value of a null field in a textbox. I can go ahead and check for DBNULL for every field in the database, but that takes so much time in "if...else" statements. Is there a way where I can write generic code to apply to all the fields? Something like:

If any field isdbnull then
appropriate textbox = ""
else
textbox = value

???
 
You can put it in a function or using DataBinding. But otherwise, theres no "magic" to a particular field and a control.

For a function, use something like:
Code:
void PutVal(object a, TextBox t)
{
    if(a==System.DBNull.Value)
        t.Text = string.empty;
    else
        t.Text = a.ToString();
}

// call it with:
PutVal(dataSet.Tables["Table1"].Rows[0]["Column1"], textBox1);
PutVal(dataSet.Tables["Table1"].Rows[0]["Column2"], textBox2);
PutVal(dataSet.Tables["Table1"].Rows[0]["Column3"], textBox3);
PutVal(dataSet.Tables["Table1"].Rows[0]["Column4"], textBox4);
// The following is the same as above, but more readable
DataRow row = dataSet.Tables["Table1"].Rows[0];
PutVal(row["Column1"], textBox1);
PutVal(row["Column2"], textBox2);
PutVal(row["Column3"], textBox3);
PutVal(row["Column4"], textBox4);

-Nerseus
 
Back
Top