Error: Unable to cast object of type 'System.DateTime' to type 'System.String'.
-
Hello experts, I got above error,I am trying to do reading data from sql and write it into csv file format.However when it read data row by row from sql then gives above error. My code is: <pre> while (dr.Read()) { strRow = ""; for (int i = 0; i < dr.FieldCount; i++) { strRow += (string)dr.GetString(i); // Gives error here if (i < dr.FieldCount - 1) { strRow += this.separator; } } sw.WriteLine(strRow); }
-
Hello experts, I got above error,I am trying to do reading data from sql and write it into csv file format.However when it read data row by row from sql then gives above error. My code is: <pre> while (dr.Read()) { strRow = ""; for (int i = 0; i < dr.FieldCount; i++) { strRow += (string)dr.GetString(i); // Gives error here if (i < dr.FieldCount - 1) { strRow += this.separator; } } sw.WriteLine(strRow); }
I also had experienced this, so i change the Get[Type]() methods such as GetString(index), GetInt16(index) etc with GetValue(i) or DataReader indexer it self, but it must be checked first if return value is DBNull. In your case replace your code in line that gives error with
KIDYA wrote:
strRow += (string)dr.GetString(i); // Gives error here
if (!Convert.IsDBNull(dr[i]){
strRow +=dr[i].ToString();
}or
if (!Convert.IsDBNull(dr.GetValue(i)){
strRow +=dr.GetValue(i).ToString();
}hope it helps
dhaim ing ngarso sung tulodho, ing madyo mangun karso, tut wuri handayani. "Ki Hajar Dewantoro" in the front line gave a lead, in the middle line build goodwill, in the behind give power support
-
Hello experts, I got above error,I am trying to do reading data from sql and write it into csv file format.However when it read data row by row from sql then gives above error. My code is: <pre> while (dr.Read()) { strRow = ""; for (int i = 0; i < dr.FieldCount; i++) { strRow += (string)dr.GetString(i); // Gives error here if (i < dr.FieldCount - 1) { strRow += this.separator; } } sw.WriteLine(strRow); }
-
I also had experienced this, so i change the Get[Type]() methods such as GetString(index), GetInt16(index) etc with GetValue(i) or DataReader indexer it self, but it must be checked first if return value is DBNull. In your case replace your code in line that gives error with
KIDYA wrote:
strRow += (string)dr.GetString(i); // Gives error here
if (!Convert.IsDBNull(dr[i]){
strRow +=dr[i].ToString();
}or
if (!Convert.IsDBNull(dr.GetValue(i)){
strRow +=dr.GetValue(i).ToString();
}hope it helps
dhaim ing ngarso sung tulodho, ing madyo mangun karso, tut wuri handayani. "Ki Hajar Dewantoro" in the front line gave a lead, in the middle line build goodwill, in the behind give power support