1

I have a subroutine to insert a record to sql server table. The code:

    public void Insert_Met(int Counts, char Gender)
    {
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        parameters.Add("@Counts", Counts);
        parameters.Add("@Gender", Gender);
        // run a stored procedure ExecuteNonQuery
    }

I other line code,

      int counts = Convert.ToInt32(numberUpdowncontrol1.Text);
       // from a control, maybe empty then it is null.
      Insert_Met(counts,'M');

My question is sometimes Counts can be null, so how to change my code?

Thanks,

  • Your "other line code" is not valid - you should show **real code**, as it helps us work with you better. – Reed Copsey Jun 13 '12 at 16:07
  • 2
    Do you *really* have a `Text` property which is assignable to an `int` variable? – Jon Skeet Jun 13 '12 at 16:07
  • @Jon, it is a numericupdown control in windows form. I feel that it is hard to assign a text to an int variable. How to change it? –  Jun 13 '12 at 16:12
  • @Love: For one thing, don't post code which doesn't compile... but then I'd use the `Value` property, which returns a `decimal`. You can then convert that to an integer just by casting, if you're certain that it won't lose any important information. Note that it still won't be null... – Jon Skeet Jun 13 '12 at 16:19
  • @Love I edited my post to include one option which checks for whether the user's set the control to empty (hit delete) but also does the cast to integer values for you... – Reed Copsey Jun 13 '12 at 16:20

3 Answers3

11

You could use int? counts instead of int counts, and check the value within your method:

public void InsertMet(int? counts, char gender)
{
    Dictionary<string, object> parameters = new Dictionary<string, object>();
    parameters.Add("@Counts", counts.HasValue ? counts.Value : (object)DBNull.Value);
    parameters.Add("@Gender", gender);
    // run a stored procedure ExecuteNonQuery
}

it is a numericupdown control in windows form. I feel that it is hard to assign a text to an int variable. How to change it?

In order to set the count value appropriately for the above, you could do:

int value = (int)numberUpdowncontrol1.Value;
int? counts = !string.IsNullOrEmpty(numberUpdowncontrol1.Text) ? value : (int?)null;

InsertMet(counts, 'M');
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

Following statement will always produce not null value

int counts = Convert.ToInt32(null); // Result is 0
Pankaj
  • 9,749
  • 32
  • 139
  • 283
0
int count = !(count == 0)? count ? (object)DBNull.Value

-If, count is not zero save the count value to database -If it is zero save

priyanka
  • 159
  • 1
  • 3