1

I have the following code. When I use breakpoints, I can see that ["@myID"].Value is a real value, such as 2467. However, I'm not able to cast that as a string for my tryParse. I've tried using "as string" like below, and I've also tried toString(). My stringID remains null, so the tryParse leaves the myID value as a zero. I'm sure it's a trivial syntax issue, but I'm stumped. I need to return a real ID such as 2467, etc.

public static int myMethod(string name)
{
    Database myDB = DatabaseFactory.CreateDatabase("myDatabase");
    DbCommand myCommand = myDB.GetStoredProcCommand("myStoredProc");

    myDB.AddInParameter(myCommand, "@Name", DbType.String, name);
    myDB.AddOutParameter(myCommand, "@myID", DbType.Int32, 4);

    int myID = 0;

    int test = myDB.ExecuteNonQuery(myCommand);
    string stringID = myCommand.Parameters["@myID"].Value as string;
    bool canParse = int.TryParse(stringID, out myID);
    return myID;
}
WEFX
  • 8,298
  • 8
  • 66
  • 102

2 Answers2

3

My guess is that the cast is failing. You are declaring the OUT param as INT, you should attempt to read it back as int as well:

int stringID =(int) myCommand.Parameters["@myID"].Value ;

And I don't think you need to attempt to parse it again on the next line. myCommand.Parameters["@myID"].Value should already contain the value.

Icarus
  • 63,293
  • 14
  • 100
  • 115
  • Right you are; mostly. I had to cast as int with an explicit cast; I couldn't use "as int". – WEFX Oct 26 '11 at 00:46
2

Also you can use "Convert.ToInt32" function

int stringID = Convert.ToInt32(myCommand.Parameters["@myID"].Value) ;
WEFX
  • 8,298
  • 8
  • 66
  • 102
Jacky
  • 1
  • 4