Pass null values from C # to sql server

2

At the moment I am making a form in which I hide some fields in order to fill them when editing.

The drawback is that clicking on save generates an error of type La cadena de entrada no tiene el formato correcto. and is because the fields that I have hidden receive values of type ditetime , but as I have hidden them I do not add a value of that type of data. What I need to do is send those fields null to those fields. I tried the following but I still can not get it

if (!string.IsNullOrEmpty(TextBoxFechainicial1.Text))
   fc.fecha_cuota_inic1 = DateTime.Parse(TextBoxFechainicial1.Text);'

if (!string.IsNullOrEmpty(TextBoxFechainicial2.Text))
   fc.fecha_cuota_inic2 = DateTime.Parse(TextBoxFechainicial2.Text);

How else can I do it?

    
asked by Andrex_11 12.05.2018 в 00:53
source

3 answers

6

Uses nullables on the property:

DateTime? fecha_cuota_inic1 {get; set;}
DateTime? fecha_cuota_inic2 {get; set;}

or in this other way (it's the same):

Nullable<DateTime> fecha_cuota_inic1 {get; set;}
Nullable<DateTime> fecha_cuota_inic2 {get; set;}

Assuming, of course, that you have designed your table with those two fields that allow null.

EDIT Source: link

    
answered by 12.05.2018 / 02:58
source
1

I solved it by giving it the minimum value

DateTime FechaNull = DateTime.MinValue;

now just check

if (FechaNull == DateTime.MinValue)
{
...
}
    
answered by 12.05.2018 в 21:54
1

Properties type null

DateTime? fecha_cuota_inic1 { get; set; }
DateTime? fecha_cuota_inic2 { get; set; }

In the data access class you could do something like this:

var connection = new SqlConnection("stringConnection");
var command = new SqlCommand("command", connection);
command.Parameters.AddWithValue("@param1", obj.fecha_cuota_inic1 ?? DbNull.Value);
command.Parameters.AddWithValue("@param2", obj.fecha_cuota_inic2 ?? DbNull.Value);

The field of the table you want to modify must allow null values

    
answered by 14.05.2018 в 22:26