Storing Number in an integer from sql Database
i am using database with table RESUME and column PageIndex in it which type is number in database but when i want to store this PageIndex value to an integer i get exception error
Specified cast is not valid.
here is the code
string sql;
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Deliverable4.accdb";
protected OleDbConnection rMSConnection;
protected OleDbDataAdapter rMSDataAdapter;
protected DataSet dataSet;
protected DataTable dataTable;
protected DataRow dataRow;
on Button Click
sql = "select PageIndex from RESUME";
rMSConnection = new OleDbConnection(conString);
rMSDataAdapter = new OleDbDataAdapter(sql, rMSConnection);
dataSet = new DataSet("pInDex");
rMSDataAdapter.Fill(dataSet, "RESUME");
dataTable = dataSet.Tables["RESUME"];
int pIndex = (int)data开发者_开发知识库Table.Rows[0][0];
rMSConnection.Close();
if (pIndex == 0)
{
Response.Redirect("Create Resume-1.aspx");
}
else if (pIndex == 1)
{
Response.Redirect("Create Resume-2.aspx");
}
else if (pIndex == 2)
{
Response.Redirect("Create Resume-3.aspx");
}
}
i am getting error in this line
int pIndex = (int)dataTable.Rows[0][0];
If it can't cast it to an integer, then it isn't retrieving it as one from the database. What is the data type of the field?
Try examining the results of dataTable.Rows[0][0].GetType().ToString()
to see what the object actually is.
You say "type is number in database" - it sounds as though this might be numeric
, in which case the most appropriate match in .NET-land is decimal
. If you know it is an int, you can simply cast it from decimal
to int
afterwards:
int pIndex = (int)(decimal)dataTable.Rows[0][0];
May I very humbly suggest a different way of doing this?:
string conString = "..."; // <-- your connection string
using (IDbConnection connection = new OleDbConnection(conString))
{ // ^^^ interface type makes your code less dependent on a particular backend!
connection.Open();
try
{
using (IDbCommand command = connection.CreateCommand())
{ // ^^^ ditto
command.CommandText = "SELECT PageIndex FROM RESUME";
object scalar = command.ExecuteScalar();
// ^ ExecuteScalar reads the first value in the first column
// of the result set; or returns null if it fails to do so.
if (scalar == null) throw ...; // unexpected result from database!
if (scalar == DBNull.Value) throw ...; // ditto!?
int pIndex = (int)scalar;
switch (pIndex)
{
case 0: Response.Redirect("Create Resume-1.aspx"); break;
case 1: Response.Redirect("Create Resume-2.aspx"); break;
case 2: Response.Redirect("Create Resume-3.aspx"); break;
default: throw ...; // unexpected result from database!?
}
}
}
finally
{
connection.Close(); // (will execute even when exceptions are thrown!)
}
}
I solved the problem.
int pIndex = int.Parse(dataTable.Rows[0][0].ToString());
精彩评论