0

I have some textbox which can have empty value. When I am trying to insert that textbox.text in insert command then it show error in sql. I want the automatic check when textbox is empty it will insert null in database in sql server 2008 R2. I am using normal insert into command and I do not want to use procedure(too clumsy). please help me anyone.

Thanks in advance.

1
  • 2
    What is the table structure and what is the datatype and make it nullable field. Commented May 7, 2013 at 5:05

3 Answers 3

4

Not really sure about your code, but it should be like:

using (SqlConnection conn = new SqlConnection("ConnectionString"))
using (SqlCommand cmd = new SqlCommand())
{
    cmd.CommandText = "INSERT into yourTable(ID, Col1, Col2) VALUES (@ID, @Col1, @Col2);";
    cmd.Connection = conn;
    conn.Open();
    cmd.Parameters.AddWithValue("@ID", yourID);
    cmd.Parameters.AddWithValue("@Col1", string.IsNullOrWhiteSpace(textBox1.Text) ? 
                                          DBNull.Value: textBox1.Text);
    cmd.Parameters.AddWithValue("@Col2", string.IsNullOrWhiteSpace(textBox2.Text) ?
                                          DBNull.Value : textBox2.Text);
    cmd.ExecuteNonQuery();
}

You can check for Empty String using string.IsNullOrWhiteSpace, pass null accordingly. Use string.IsNullOrEmpty(), if you want to consider spaces as valid values.

Sign up to request clarification or add additional context in comments.

5 Comments

A string consisting of blank characters (say, a single space) if not empty, but you're treating it as empty. I cannot tell whether that's what the OP wants, but it's not what the OP asks for, that's simply string.IsNullOfEmpty.
@hvd, I can only guess that the OP would consider whitespaces as empty, but you are right I should add that in my answer.
Yes, inserting null pre-edit was not the right call - DBNull.Value being the key. Otherwise very clear, explanatory code from the start.
@J0e3gan, yes, using ORM frameworks, I got use to null rather than DBNull.Value :)
Fair enough. We're roughin' it in this case. :)
1

If you are using direct insert query

"insert into table_name (column1,column2,column3) values("+column1value+","+column2value+","+textbox.Text.Trim()!=""?textbox.Text.Trim():DBNull.Value+")";

Even if you are using parameterised query, you can use the same expression

textbox.Text.Trim()!=""?textbox.Text.Trim():DBNull.Value

2 Comments

This example is a candidate for SQL injection. I would always recommend using parameters and not directly building sql statements by injecting text that's provided by users. At minimum, you should ensure that you are escaping SQL characters.
Sorry, you are correct. parameterised query is always better. Dont use direct queries, will lead to sql injection. Thank you for reminding me.
0

Try something like this:

using (SqlConnection conn = new SqlConnecction(connStr))
{
    conn.Open();
    string qry = "INSERT TargetTable (TargetColumn) VALUES (@TextValue)";
    using (SqlCommand cmd = new SqlCommand(qry, conn))
    {
        cmd.Parameters.Add(new SqlParameter("@TextValue", String.IsNullOrEmptyOrWhiteSpace(textBox.Text) ? DBNull.Value : textBox.Text));
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (SqlException sex)
        {
            // whatever
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.