Hi all,
I had an intention to query one table and insert some value into another table. There is no problem in querying the table with value. But if the value is null, it throws a invalidcastexception - Unable to cast object of type 'System.DBNull' to type 'System.String'
Part of my code is as follow.
Can anyone let me know how to handle data that is null
Thanks
while (reader.Read()){
for (int i=0;i<20;i++){
if (reader.GetString(i) != null){
result = reader.GetString(i).ToString();
}
else{
result =
" ";}
data = data +
"'\" + " + result + " + \"', ";}
data = data.Substring(0, data.Length - 2);
}
MessageBox.Show(data); // close reader and connectionreader.Close();
conn.Close();

How to handle null value
Amr Mahmoud
> if (reader.GetString(i) != System.DBNull)
I think that will still throw an exception, you should check for DBNull before calling GetString, e.g.:
result = reader.IsDBNull(i) "" : reader.GetString(i);
decrypted
if (reader.GetString(i) != null)
withif (reader.GetString(i) != System.DBNull)