int cg = Convert.ToInt16(comboBox1.SelectedValue.ToString());

This code is giving an error. Please tell me where I m wrong.

7 Years
Discussion Span
Last Post by litlemaster


Are you getting error like "Object reference not set to an instance of an object."? If so,
validate null values before converting to int.

Here is a way of validating;

int cg=0;
if (comboBox1.SelectedValue != null)
   cg = Convert.ToInt16(comboBox1.SelectedValue.ToString());

Good luck.

Edited by MeSampath: n/a


Int16 cg = Convert.ToInt16(comboBox1.SelectedValue.ToString());

or if your int value is large,
use Int32 or Int64


well the problem has been solved for me. Now I am not using this piece of code. But to share with you , I was getting an Exception whenever I tried to run the project. The exception was.
Input string was not in a correct format.


Actually I had to use that string variable in a query in which I have to select a column having int data type.
I simply changed my database schema and modified that column to hold String data. And My problem was solved. I know this is not the ultimate solution for the problem, but i have to adopt it in order to run my project in some way or the other. But I still want to know why I was not able to convert that string to int. As the exception suggests that there was some problem in specifying String, that's why I thought that my Syntax might be wrong as I have very little practice with c#.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.