简体   繁体   English

C#中带有变量的奇怪行为

[英]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. 我使用的是sqlDataSource,它从数据库中拉出许多行,具体取决于从下拉列表中选择的行数。 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. MealNumberDD是我的下拉菜单的ID。 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. 从MealNumberDD.SelectedValue到“ 3”,查询运行完美,信息显示在网格中。 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. 我试过string s = MealNumberDD.Text声明string s = MealNumberDD.Text并使用s作为最后一个参数,但这无济于事。 Ive outputted the return value of MealNumberDD to an OutputLabel, and it outputs as expected. Ive将MealNumberDD的返回值输出到OutputLabel,并按预期输出。 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. 您添加参数的方法会将param值添加为字符串。 MSDN 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 您试图将字符串值传递到分类为Int32

What you could do is parse your value first into a int (Maybe using TryParse ) 您可以做的是先将您的值解析为一个int(也许使用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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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