0

I'm working with several forms and so far I've figured that there really is no way to take an empty text field and insert it into a database as null.

for example if the text field is empty in:

<asp:TextBox id="tb0" runat="server"></asp:TextBox>
<asp:TextBox id="tb1" runat="server"></asp:TextBox>
<asp:TextBox id="tb2" runat="server"></asp:TextBox>

But filled in the textboxes surrounding it

Is there any way for the query to, when run, look like this:

INSERT INTO table_name VALUES ('test0', null, 'test2')

Instead of having to loop through and changing the values to whitespace? The whitespace is fine when they are varchar fields but for ints/dates it is very annoying

Here is a part of one of my inserts

"INSERT INTO Customer VALUES(" + custID + " , @mastName, @custName, @addrLn1, @addrLn2, @cCity, @cState, @cZip, @cZip4, @cCountry, @cusSince, @renewalDate)"

BTW custID is not a parameter because it is a float and when I set it as a parameter the value gets messed up (e.g 105.05 will turn into 105.0498..)

brianforan
  • 184
  • 2
  • 15
  • Can you show the code where you are actually preparing and executing the database inserts? – Nathan A Jul 09 '14 at 17:06
  • If you'd start with parametrized queries (as you must) you'd be easily specify DBNull as parameter type of nullable column... This already covered in http://stackoverflow.com/questions/16717179/how-to-insert-null-value-in-database-through-parameterized-query – Alexei Levenkov Jul 09 '14 at 17:06
  • I updated OT and correct me if I'm wrong but DBNull looks like it prepares the field to be null, this is optional? Is that what it does? I'm new to c# so bare with me.. edit: after reading some of the thread I see what you mean, I will give that a shot – brianforan Jul 09 '14 at 17:23

4 Answers4

2

You could use a simple method like this:

object ToDBValue(string str)
{
    return string.IsNullOrEmpty(str) ? DBNull.Value : (object)str;
}

Then you could build your parameters:

command.Parameters.AddWithValue("@VAL1", ToDBValue(tb0.Text));
command.Parameters.AddWithValue("@VAL2", ToDBValue(tb1.Text));
command.Parameters.AddWithValue("@VAL3", ToDBValue(tb2.Text));

And then change your query to:

INSERT INTO table_name VALUES (@VAL1, @VAL2, @VAL3)
itsme86
  • 19,266
  • 4
  • 41
  • 57
1

use DBNull.Value which will give you Null for that specific value in the row. So if your checking if the textbox is null. Just use something along the lines of !string.IsNullOrWhitespace(tb0.Text) ? tb0.Text : DBNull.Value

AlanWalker
  • 19
  • 1
0

If your using a stored procedure with parameters you can make a paramenter value DBNull.Value

Hillboy
  • 472
  • 6
  • 19
0

Can you change the stored procedure? If so, you can make the parameter optional, defaulting to NULL and just not pass it is the value IsNullOrEmpty.

BanksySan
  • 27,362
  • 33
  • 117
  • 216