如何将数据集列值转换为整数

时间:2014-05-18 15:13:59

标签: c# asp.net dataset sql-server-express

public DataSet ds = new DataSet();
public SqlDataAdapter adapter = new SqlDataAdapter();

public int AuthenticatedUserAge(String User_name)
{
    string sql = "SELECT UserName, Age FROM tblDataProg WHERE (UserName ='" +   User_name  + "')";
    ds = GetDataSet(sql);
    int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
    return help;    
}

public DataSet GetDataSet(string sql)
{
    SqlConnection connection = new SqlConnection(ConnStr());
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = sql;
    cmd.Connection = connection;
    adapter = new SqlDataAdapter(cmd);
    connection.Open();
    adapter.Fill(ds);
    connection.Close();
    return ds;
}    

public string ConnStr()
{
    return @"Data Source=.\SQLEXPRESS;AttachDbFilename='G:\עבודת גמר תכנות\v5\חדש תיקיה 1\v4\App_Data\SiteDB.mdf';Integrated Security=True;User Instance=True";
}

我需要检查从AuthenticatedUserAge返回的值是否小于17,它将写入你好少年其他人写你好成人。

我认为问题是这一行没有返回值:
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
它抛出了这个错误:

  

输入字符串的格式不正确

5 个答案:

答案 0 :(得分:0)

这不是一个真正的答案,但在评论中不会很清楚。

打破这一行:

int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());

分为:

//set a breakpoint on the next line
string temp = ds.Tables[0].Rows[0]["Age"].ToString(); 
//take one step (F10) over the break and hover over temp
//or use a watch.  What is the value of temp?
int help = int.Parse(temp);

答案 1 :(得分:0)

数据库中该用户年龄的值必须为NULL 您需要检查NULL,为了安全起见,您还应该检查数据库中没有返回任何结果。

public int AuthenticatedUserAge(String User_name)
{
    string sql = "SELECT UserName, Age FROM tblDataProg WHERE (UserName ='" +   User_name  + "')";
    ds = GetDataSet(sql);
    //check for no results
    if(ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
    {
       return 0;
    }
    //check for null
    if(ds.Tables[0].Rows[0]["Age"] == DBNull.Value)
    {
       return 0;
    }
    int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
    return help;    
}

此外,你真的不应该使用动态SQL - 请使用参数代替。阅读this

答案 2 :(得分:0)

使用TryParse方法来防止错误:

public int AuthenticatedUserAge(String User_name)
{
    string sql = "SELECT UserName, Age FROM tblDataProg WHERE (UserName ='" +   User_name  + "')";
    ds = GetDataSet(sql);
    int help = 0;
    int.TryParse(ds.Tables[0].Rows[0]["Age"].ToString(), out help);
    return help;    
}

使用上面的代码,如果发生错误,help的值将保持其初始化值(在本例中为0)。

答案 3 :(得分:0)

试试这个。它会对你有所帮助。

int help = Convert.ToInt32(ds.Tables[0].Rows[0]["Age"]);

答案 4 :(得分:0)

可能年龄字段为空,您可以使用它来识别和设置默认值。

response = b.shorten(storeURL)
shortURL = response['url']