Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to get return value from a stored procedure to a list box

Status
Not open for further replies.

Saturn57

Programmer
Aug 30, 2007
275
CA
I have the following code that tries to get a return value @quotenum from a stored procedure but in my code i get the error that @quotenum is an unassigned local variable. Any help would be appreciated.

private void approveestBN_Click(object sender, EventArgs e)
{
{
int estno;
int endestno;
int.TryParse(endTB.Text, out endestno);
int @quotenum;


if (int.TryParse(startestnoCB.Text, out estno))
while (estno <= endestno)
{
SqlConnection conn = new SqlConnection("Data Source=server1;Initial Catalog=estimator;Integrated Security=True");
SqlCommand cmd = new SqlCommand("QuoteCreate", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Estnum", estno);

try
{
conn.Open();

cmd.ExecuteNonQuery(); // If you do not need a return;

quotesLB.Items.Add (@quotenum);

estno = estno + 1;

}
catch (SqlException err)
{
MessageBox.Show(err.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
}
}
}
 
I don't think cmd.ExecuteNonQuery is right because you're looking for a value, I think you have to use ExecuteScalar to pick up the value. The error is to do with the variable @quotenum, it's possible in your code that this will never be populated so declare it and initialize it

Code:
int @quotenum = 0;

Patrick
 
Changing to ExecuteScalar and initializing @quotenum = 0 did not work
 
ExecuteQuery and ExecuteScalar both return a value, but with significant differences, depending on the sp.

ExecuteQuery always returns an integer value which is the actual *return* value when the stored procedure exits.

ExecuteScalar returns the first value of the first column only. The datatype can be other than integer.

In both cases, you need to hold the returned value. Im guessing your variable *quotenum* is for that purpose.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top