如何将var类型变量转换为int [英] how to convert var type variable to int

查看:872
本文介绍了如何将var类型变量转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ForEach循环中使用var类型变量,我正在为它整数arry如何将其转换为int类型,下面是我的代码

i am using var type variable in ForEach loop and i am assining it integer arry how can i convert it to int type, below is my code

foreach (var item in this.checkedListBox1.CheckedItems)
           {        
                  
                       da.ProcName = "AssignSubjectToStudent";//calling stored procedure
                       da.OpenDBConnection();
                       da.CreateCommandObject();         
                   da.Parameters("@KeyStudent", int.Parse(txtStudent.SelectedValue.ToString()));
                       da.Parameters("@KeySubject",int.Parse(item) );// it can not be converted
                       da.ExecuteNonQuery();
                 
           }
           da.CloseConnection();
           empty();

推荐答案

您好,

如果您使用 CheckedListBox 然后通过这种方式找到任何项目

Hello ,
If you are using CheckedListBox then find any item by this way
(string)checkedListBox1.Items[i];//here i is the position of the selcted value



现在将此值放入商店程序

谢谢


Now put this value into the store procedure
thanks



您可以使用 Convert.Int32(item)



请问,为什么你之后,当你要将它转换为 int 时,使用 var ?如果你把它声明为 int 并且之后不转换它会不方便?
Hi,
You can use Convert.Int32(item)

May I ask, why do you use var when you're going to convert it to int afterwards? Isn't it more convenient if you declare it as int and not to convert it after?


var应该用于你不确定返回的数据类型的区域。



你打算将值转换成int,所以我想你知道数据类型。 />


您不能总是期望转换,因为它实际上取决于变量中存在的数据。您可以尝试避免以下错误:







var is supposed to be used in areas where you are not really sure of the datatype which is returned.

You intend the value to be converted into a int so I suppose you know the datatype.

You cannot always expect a conversion as it actually depends on the data present in your variable. You can instead try to avoid errors with the following:



int nNumber = -1;

bool bIsConversionDone = Int32.TryParse(item, out nNumber);

if(!bIsConversionDone)
{
    //Conversion failed
    nNumber = -1;
}

da.Parameters("@KeySubject",int.Parse(nNumber) );// it can not be converted


这篇关于如何将var类型变量转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆