【问题标题】:"data is null" when using SqlDataReader [duplicate]使用 SqlDataReader 时“数据为空”[重复]
【发布时间】:2014-03-26 19:34:42
【问题描述】:

我的代码中的最后一个字符串有问题。

这是我的代码:

private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
            string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*****";
            string Query = "select * from RMSCRMTest.dbo.sales where LastName= '" + comboLname.Text + "' ;";


            SqlConnection Myconn = new SqlConnection(conn);
            SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
            SqlDataReader Reader;
            try
            {
                Myconn.Open();
                Reader = cmdDataBase.ExecuteReader();
                while (Reader.Read())
                {
                    string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
                    string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber")).ToString();
                    string Time = Reader.GetDateTime(Reader.GetOrdinal("Time")).ToString();
                    string Deposit = Reader.GetDecimal(Reader.GetOrdinal("Deposit")).ToString();
                    string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
                    string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
                    txtid.Text = ID;
                    txtacnum.Text = AccountNuber;
                    txttime.Text = Time;
                    txtdeposit.Text = Deposit;
                    txtlname.Text = slastname;
                    txtstatus.Text = status;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Myconn.Close();
            }
}

此问题显示,因为我在表中添加了另一列并为该列创建了字符串 字符串

sstatus = Reader.GetString(Reader.GetOrdinal("status"));

我得到的错误是

数据为 null 不能对 null 值调用此方法或属性

其他字符串工作正常。

【问题讨论】:

    标签: c# sql-server sqldatareader


    【解决方案1】:

    您需要使用SqlDataReader.IsDBNull 方法检查可空字段:

    int statusIndex = Reader.GetOrdinal("status");
    string sstatus = Reader.IsDBNull(statusIndex) ? null : Reader.GetString(statusIndex);
    

    【讨论】:

    • 我用你的替换了我的行,我得到“无法将'system.Int32'类型的对象转换为系统字符串'”
    • 对不起,我做的不对,让我再检查一遍,谢谢
    • 非常感谢您,请您解释一下为什么我必须添加 int,因为此列是 varchar,而且我对这个世界真的很陌生
    • 您正在查看该索引处的数据是否为空。如果是,则返回 null。否则,获取字符串。
    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多