2
Answers

OLEDBReader Porblem

Zeb Rehman

Zeb Rehman

13y
1.8k
1
Hi every body!
                I'm facing the problem in following code. In database there is an empty field when i try to read it the error came on console. the code is given following.

It show me the error that System.InvalidCastException: Specified cast is not valid. How to remove the error.....



try

{





conn.Open();



string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;data source=Z:\\ptcl.accdb";OleDbConnection conn = new

OleDbConnection
(connectionString);string sql = "SELECT * FROM 51";OleDbCommand cmd = new OleDbCommand(sql, conn);



reader = cmd.ExecuteReader();



OleDbDataReader reader;String name = null;
string name = null;
while
(reader.Read())
{       
        if(reader.GetString())
        {
                Console.WriteLine("Feild Empty");
        }
}
}

catch(Exception ex)

{

Console.WriteLine(ex.ToString());


}



Answers (2)
0
Ryan Alford
NA 2.3k 891.7k 16y
in the Designer view, click on the grid, then click on the little arrow at the top right of the control.  This will open a "pop-up" window.  Choose "Edit Columns".  For the columns that you will have null, there is a property called "DefaultCellStyle".  click that and open the next window and you will see a property for "Null Value".  this value is what will show if the value is null.

or, the simpler method, don't allow nulls to come from the database.  Use Oracle's NVL() method to set a "default" value to if there is a null value.

ex.

SELECT
NVL(Customer_Name, ' ') AS 'Customer Name'
FROM Customer

that will return a blank space if the customer name is null. 

It's never good practice to have null values coming from a database query.