简体   繁体   中英

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.Text Beforehand 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.

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;

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM