【发布时间】:2013-10-06 03:51:16
【问题描述】:
我将变量从 List 类传递到 C# gridview。一切顺利,除非我包含返回 int 值的数据库列。如何将结果集的列值传递到列表中?导致错误的列是“本地”变量。
public class shuffleDataList
{
public string directLine { get; set; }
public int local { get; set; }
public string employeeNumber { get; set; }
}
List<shuffleDataList> callList = new List<shuffleDataList>();
if (rdr != null)
{
if (rdr.HasRows)
{
while (rdr.Read())
{
callList.Add(new shuffleDataList()
{
directLine = rdr.IsDBNull(0) ? null : rdr.GetString(0),
local = rdr.IsDBNull(1) ? 0 : rdr.GetInt32(1),
employeeNumber = rdr.IsDBNull(2) ? null : rdr.GetString(2),
});
}
}
代码将返回:
“指定的转换无效。”
我已经尝试过 GetInt32(按照上面的代码),但仍然没有解决问题。同样,如何将结果集的列 int 值传递到列表中?非常感谢您。
【问题讨论】:
-
是
local = rdr.IsDBNull(1) ? 0 : rdr.GetInt32(1)这一行吗,你确定它总是包含Int32吗? -
代码看起来不错,数据可能包含字符串而不是 int?在这种情况下,你必须解析它
-
索引为1的列有什么类型(将
rdr[1]添加到观察列表并查看结果)? -
GetInt32将列值设为Int32类型,所以我认为您的索引为 1 的列不包含可以转换为整数的值。跨度> -
嗨。本地 = rdr.IsDBNull(1) ? 0 : rdr.GetInt32(1),是我的问题所在。局部变量以我的查询中名为“Local”的列命名。该列是数字数据类型,我假设在 C# 上使用 int 数据类型将检索它