FormatException: Input string was not in the correct format
I have Views field from one of my tables in the database. At first i allowed it to take nulls, and now it disallowed it to take null. The problem is that that exception is being thrown when i convert the SqlReader instance to an int..here is the code:
try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr != null && dr.Read() && dr["Views"] != null && dr["PageNumber"] != null && dr["Replies"]!=null)
{
Name = dr["Name"].ToString();
ThreadName = dr["ThreadTitle"].ToString();
Views = int.Parse(dr["Views"].ToString());//it is being thrown here when i try to convert it to an int..How can i prevent that mistake from being thrown?
Replies = int.Parse(dr["Replies"].ToString());
Topic = dr["Theme"].ToString();
Subtopic = dr["Topics"].ToString();
PageNumber = int.Parse(dr["开发者_运维百科PageNumber"].ToString());
Time = (DateTime)dr["Time"];
}
dr.Close();
}
Try
View = dr["Views"] as int? ?? 0;
If the value in the db is null then above it's being cast into a nullable int which can accept nulls.
Use the coalesce operator ?? to set the value of View to some other value (in this case 0) if the value in the database IS null.
You can use int.TryParse() to avoid the error. If the probem is just the null, I would recommend to use System.Convert to handle these situations, because it's safer and clear:
View = System.Convert.ToInt32(dr["Views"]);
To avoid exception while convertion, use Int32.TryParse always.
How about
if(dr["Views"] != DBNull)
{
// do your parse here
}
精彩评论