【问题标题】:"Input string was not in a correct format" when using SqlDataReader and Label使用 SqlDataReader 和 Label 时“输入字符串的格式不正确”
【发布时间】:2009-08-20 16:07:45
【问题描述】:

我在 Select 语句中加入两个表 - Contact 和 RetailTrainingUserLevelMap。

(两者的共同列是 RetailTrainingUserLevelID int)

选择 Contact.IntranetUserName、Contact.CompanyName、RetailTrainingUserLevelMap.RetailTrainingUserLevel

来自联系人

INNER JOIN RetailTrainingUserLevelMap ON Contact.RetailTrainingUserLevelID = RetailTrainingUserLevelMap.RetailTrainingUserLevelID

AND Contact.RetailTrainingUserLevelID = RetailTrainingUserLevelMap.RetailTrainingUserLevelID

WHERE (Contact.IntranetUserName = @IntranetUserName)


如果我通过 Visual Studio 查询生成器(测试查询窗口)运行此语句,并为“IntranetUserName”输入一个值,我会得到:

内网用户名:
约翰·乔

公司名称:
Acme Inc.

RetailTrainingUserLevel:
经理

这是我想要的输出,到目前为止一切顺利。

如果我在我的 .cs 代码隐藏中使用相同的选择语句,使用 SqlDataReader 将标签绑定到其中一些列,如下所示:

SqlCommand comm;
        SqlConnection conn;
        string intranetConnectionString = ConfigurationManager.ConnectionStrings["DataConnect"].ConnectionString;
        conn = new SqlConnection(intranetConnectionString);
        comm = new SqlCommand("SELECT Contact.IntranetUserName, Contact.CompanyName, RetailTrainingUserLevelMap.RetailTrainingUserLevel FROM Contact INNER JOIN RetailTrainingUserLevelMap ON Contact.RetailTrainingUserLevelID = RetailTrainingUserLevelMap.RetailTrainingUserLevelID AND Contact.RetailTrainingUserLevelID = RetailTrainingUserLevelMap.RetailTrainingUserLevelID WHERE (Contact.IntranetUserName = @IntranetUserName)", conn);

        comm.Parameters.Add("@IntranetUserName", System.Data.SqlDbType.VarChar, 50);
        comm.Parameters["@IntranetUserName"].Value = memberLoginName;

        conn.Open();
        SqlDataReader reader = comm.ExecuteReader();
        while (reader.Read())
        {
            memberCompanyNameLabel.Text += reader["CompanyName"];
           userLevelLabel.Text += reader["RetailTrainingUserLevel"];
        }

        reader.Close();
        conn.Close();

我收到错误“输入字符串的格式不正确。”这里:
userLevelLabel.Text += reader["RetailTrainingUserLevel"];

这里需要更改什么 C# 语法,以便我可以将该值正确绑定到我的 userLevelLabel?

注意: RetailTrainingUserLevelID 整数
RetailTrainingUserLevel varchar (50)

感谢您的时间和知识。

【问题讨论】:

  • 道格,12 年后你有没有想过这个问题?...

标签: c# label inner-join string-formatting


【解决方案1】:

您确定 reader["RetailTrainingUserLevel"] 不是 DBNull?

在尝试将其添加到另一个字符串之前,可能需要对其执行 .ToString()。

我会做的

userLevelLabel.Text += reader["RetailTrainingUserLevel"].ToString();

【讨论】:

  • 嗨 Stan,“RetailTrainingUserLevel”设置为不允许为空。我尝试了您的代码建议,但仍然收到错误消息:“输入字符串的格式不正确。”在 userLevelLabel.Text += reader["RetailTrainingUserLevel"].ToString();我很困惑为什么会出现问题。读者想要一个“RetailTrainingUserLevel”值,在表中设置为 varchar - 可能的值是 Manager、Supervisor、Principal,它们对我来说都像是字符串。不知道还有什么可以尝试的。我的 JOIN 语句设置不正确吗?感谢您提出任何其他想法...
猜你喜欢
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2013-08-22
相关资源
最近更新 更多