Judah Schwartz
Judah Schwartz

Reputation: 1

Strange behavior with variables in c#

I'm using a sqlDataSource that pulls a number of rows from a database, depending on which number is seleted from a dropdown. Here is my codebehind code:

var query = "SELECT TOP (@MealNumber)  * FROM Recipes";
RecipesDataSource.SelectCommand = query;
RecipesDataSource.SelectParameters.Add("MealNumber", DbType.Int32,MealNumberDD.SelectedValue);

MealNumberDD is the ID for my dropdown. When I switch the last parameter of

RecipesDataSource.SelectParameters.Add("MealNumber", DbType.Int32,MealNumberDD.SelectedValue)

From MealNumberDD.SelectedValue to "3", the query runs perfectly and the information is displayed in a grid. When I switch it back, nothing at all is displayed.

I've tried declaring string s = MealNumberDD.TextBeforehand and using s as the last parameter, but that doesn't help. Ive outputted the return value of MealNumberDD to an OutputLabel, and it outputs as expected. Still no luck, the information isn't displayed. I've gone through the debugger as well, the variables are being passed through completely as expected. I have no idea whats going on with this.

Upvotes: 0

Views: 53

Answers (2)

nyxthulhu
nyxthulhu

Reputation: 9762

You've attempted to pass a string value into something your classifying as a Int32

What you could do is parse your value first into a int (Maybe using TryParse)

var mealNumberString = MealNumberDD.Text;
int mealNumberParsed = 0;
Int32.TryParse(out mealNumberParsed, mealNumberString);

Then you can go ahead and use it like your currently using it

RecipesDataSource.SelectParameters.Add("MealNumber", DbType.Int32,mealNumberParsed )

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

Your method to add parameter adds the param value as string. MSDN

You need to do

var s = MealNumberDD.Text;

var param = new SQLParameter("MealNumber", SQLDbType.Int)
{
    Value = Convert.ToInt32(s)
};

RecipesDataSource.SelectParameters.Add(param); 
var query = "SELECT TOP (@MealNumber) * FROM Recipes"; 
RecipesDataSource.SelectCommand = query;

Upvotes: 1

Related Questions