-1

It's pretty simple I have some textboxes to fill up and submit to SQL Server, some of them may be blank, so whenever I run the query, I get a bunch of spaces instead of the word Null in the database..

My query goes like :

 var qry = "INSERT INTO tablename  (Text,Trans, ..)
                              Values ('"TextBox1.text "','" TextBox2.text, ..)";
db.Query(qry);
user2962142
  • 1,916
  • 7
  • 28
  • 42
  • 3
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection – marc_s Jun 05 '16 at 20:19
  • im aware of that, its just a simple collage project so its not a big of a deal – user2962142 Jun 05 '16 at 20:21
  • 1
    Using **parameters** would also make it *really easy* to insert `NULL` instead of spaces ..... by assigning `param.Value = DBNull.Value;` .... – marc_s Jun 05 '16 at 20:21

2 Answers2

3

A better option would be to do something like....

SqlCommand cmd = new SqlCommand("INSERT INTO tablename  (Text,Trans) Values (@Text, @Trans)");
cmd.Parameters.Add(new SqlParameter("@Text" , string.IsNullOrEmpty(TextBox1.text) ? (object)DBNull.Value : TextBox1.text);
cmd.Parameters.Add(new SqlParameter("@Trans", string.IsNullOrEmpty(TextBox2.text) ? (object)DBNull.Value : TextBox2.text);
M.Ali
  • 67,945
  • 13
  • 101
  • 127
0

You can use NULLIF:

INSERT INTO tablename  (Text,Trans, ..)
Values (NULLIF('" + TextBox1.text + "', ''), NULLIF('" + TextBox2.text + "', ''), ..)";
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98