Search code examples
c#databasewinformsnullable

How to insert int NULL into numeric database field?


I am trying to insert a NULL value into a numeric database field from a winform textbox using C#. I am creating an app to enter production data into a database. Quantity variables are set as int? to accept null since there wouldn't be a value to enter if a piece of equipment sat down. The database fields also have a default value set to Null. How would I be able to leave a textbox blank and enter Null into the database field? I have scaled down my code to include what is affected.

private void btnInsert_Click(object sender, EventArgs e)
    {
        int? runQty = 0;
        int? scrapQty = 0;

        try
        {
            dbConn = new OleDbConnection();
            dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + strDataFilePath + ch;
            dbConn.Open();

            sql = "INSERT INTO DailyProduction (runQty, scrapQty)" +
            "Values (@runQty, @scrapQty)";

            dbCmd = new OleDbCommand(sql, dbConn);

            if (runQty.HasValue)
            {
                runQty = Convert.ToInt16(this.runQuatity.Text);
                dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = runQty;
            }
            else
            {
                runQty = null;
                dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = runQty;
            }

            if (scrapQty.HasValue)
            {
                scrapQty = Convert.ToInt16(this.scrapQuantity.Text);
                dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = scrapQty;
            }
            else
            {
                scrapQty = null;
                dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = scrapQty;
            }

            dbCmd.Connection.Close();
            dbConn.Close();

            MessageBox.Show("Record Entered!");
        }
        catch (Exception err)
        {
            MessageBox.Show("Error: " + err.Message.ToString());
        }
    }

Solution

  • You can check whatever a string is null or empty using string.IsNullOrEmpty() or string.IsNullOrWhiteSpace() methods:

    if (string.IsNullOrEmpty(textBox1.Text))
    {
        ...
    }
    

    Also, for null values you should use DbNull.Value:

    dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = DbNull.Value;
    dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = DbNull.Value;