Link to home
Start Free TrialLog in
Avatar of Stanton_Roux
Stanton_RouxFlag for South Africa

asked on

C# convert int to Null

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,
Thanks
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();
        try
        {
            DataSet ds = new DataSet();
            ds = rm.getEventDetailsForCalendar(RegionID, Month);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of gyoreg
gyoreg
Flag of Hungary image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Guy Hengel [angelIII / a3]
what about:


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

Open in new window

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.
Avatar of Stanton_Roux

ASKER

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);
.
.
.