Search code examples
c#type-conversionconventionssql

Converting a string to int, for a SQL Database call


I am trying to execute a SQL select statement to retrieve my id, then increment the id. I can select from the database just fine. But when I try to convert the string to a int, I get the error of format exception was caught

Input string was not in a correct format.

Here is my code:

var sql = new SQL_Statements();
var string_sql_id ="";
var string_sql_select = "select * from is_inventory where id =(select max(id) from is_inventory)";

var sql_ds = sql.SelectFromDB(string_sql_select);

int DataIndex;

if (sql_ds.Tables["CurData"].Rows.Count > 0)
   for (DataIndex = 0; DataIndex <= sql_ds.Tables["CurData"].Rows.Count - 1; DataIndex++)
   {
       (sql_ds.Tables["CurData"].Rows[DataIndex]["id"]).ToString();
       string_sql_id ="CurData";
       var int_sql_id = Convert.ToInt32(string_sql_id);
       ++int_sql_id;
   }

On the second to last line of code is where it throws the exception. I have tried to change the convert to something else like double, but that didn't work either. Thanks in advance for the help.


Solution

  • in the line immediately before you're convert line, you set string_sql_id ="CurData";. "CurData" is not an integer, and attempting to convert it to one will not work.

    try this instead;

    string_sql_id = (sql_ds.Tables["CurData"].Rows[DataIndex]["id"]).ToString();