C# 如果某些字段中存在空值,如何获取数据集

C# 如果某些字段中存在空值,如何获取数据集,c#,.net,dataset,C#,.net,Dataset,对于一些用户来说,BranchId是空的,因为它们是头,所有的分支都在它们下面。所以,当用户登录时,数据库返回数据集中的非字符串 对所有字段使用此代码 DataSet ds = ast.GetUserLoginInfo(Param); foreach (DataRow dr in ds.Tables[0].Rows) { if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0)

对于一些用户来说,BranchId是空的,因为它们是头,所有的分支都在它们下面。所以,当用户登录时,数据库返回数据集中的非字符串

对所有字段使用此代码

DataSet ds = ast.GetUserLoginInfo(Param);

foreach (DataRow dr in ds.Tables[0].Rows)
{
    if (ds.Tables.Count > 0)
    {
        if (ds.Tables[0].Rows.Count > 0)
        {
            _userstate.ID = Convert.ToInt32(ds.Tables[0].Rows[0]["ID"]);
            _userstate.Name = Convert.ToString(ds.Tables[0].Rows[0]["Name"]).Trim();
            _userstate.Email = Convert.ToString(ds.Tables[0].Rows[0]["Email"]).Trim();
            _userstate.Username = Convert.ToString(ds.Tables[0].Rows[0]["Username"]).Trim();              
            _userstate.GroupId = Convert.ToInt32(ds.Tables[0].Rows[0]["GroupId"]);
            _userstate.BranchId = Convert.ToInt32(ds.Tables[0].Rows[0]["BranchId"]);
            _userstate.BranchId = Convert.ToInt32(ds.Tables[0].Rows[0]["DeptId"]);
            _userstate.RoleId = Convert.ToInt32(ds.Tables[0].Rows[0]["RoleId"]);
            _userstate.IsActive = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"]);

            _siteuser.UserStat = _userstate;
        }

由于branchId可为null,ConvertToInt32会引发异常。试试这个

 _userstate.ID = Convert.ToInt32(ds.Tables[0].Rows[0]["ID"] == null ? 0 : ds.Tables[0].Rows[0]["ID"]);
 _userstate.Name = Convert.ToString(ds.Tables[0].Rows[0]["Name"] == null ? "" ds.Tables[0].Rows[0]["Name"] ).Trim();

那么?问题是什么?你把
DeptId
分配给
BranchId
我很确定你不是有意的。标题没有意义。如果某些字段中存在空值,那么如何获取数据集是什么意思?获取数据集?你已经有数据集了!错误?错误是什么?发帖。引用变量ds没有指向任何东西。它抛出编译时错误“TryParse方法没有重载只接受一个参数”@Smokingmonkey:你说得对,我更正了,它的第二个参数设置了结果。它应该会起作用。试试看
int.TryParse(ds.Tables[0].Rows[0]["BranchId",  _userstate.BranchId)