We help IT Professionals succeed at work.

C# convert int to Null

Stanton_Roux asked
I have a few drop down boxes which feed into a SQL query. The query is written so that any of the parameters can be Null and thus excluded from the query. If the selected value of any of the drop down boxes is 0 then i would like to set that parameter to null but I am getting compile time errors.
When I do Convert.ToInt32(null), it still returns 0.

pseudocode: if tddnRegionId.SelectedValue == 0 then make RegionID = null

Code below,
protected void btnGo_Click(Object sender, EventArgs e)
        int RegionIDNull = Convert.ToInt32(null);
        int RegionID; 

        RegionID = Convert.ToInt32(tddnRegion.SelectedValue) == 0 ? RegionIDNull : Convert.ToInt32(tddnRegion.SelectedValue);
        int Month = Convert.ToInt32(tddnMonth.SelectedValue);

        ResultsManager rm = new ResultsManager();
            DataSet ds = new DataSet();
            ds = rm.getEventDetailsForCalendar(RegionID, Month);

Open in new window

Watch Question


Try to use one of these:

int? Month

Nullable<int> Month
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

what about:

 RegionID = Convert.ToInt32(tddnRegion.SelectedValue) == 0 ? null : Convert.ToInt32(tddnRegion.SelectedValue);

Open in new window

AndyAinscowFreelance programmer / Consultant

The integer value of null is 0 (zero).  So your code <int RegionIDNull = Convert.ToInt32(null)> is doing what you programmed it to do.

angelIII: You're right, but you cannot assign null value to a value type, except if it is nullable, as I mentioned above.


Thanks all,

This is what I did to make it work

 protected void btnGo_Click(Object sender, EventArgs e)
        int? RegionID = null;

        RegionID = Convert.ToInt32(tddnRegion.SelectedValue) == 0 ? RegionID : Convert.ToInt32(tddnRegion.SelectedValue);