简体   繁体   English

将对象转换为字符串有错误

[英]converting object to string has error

My code is this : 我的代码是这样的:

SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
                   SqlCommand scm = new SqlCommand("SELECT Name FROM Table WHERE (Blogger = @Blogger)", scn);
                   scm.Parameters.AddWithValue("@Blogger", lblBloger.Text);
                   scn.Open();
                   MyLabel.Text = scm.ExecuteScalar().ToString();
                   scn.Close();

in this line : 在这一行:

lblLastNo.Text = scm.ExecuteScalar().ToString();

Has this error : 有这个错误:

Object reference not set to an instance of an object. 你调用的对象是空的。

or when I using if statement , shows same error 或者当我使用if语句时,显示相同的错误

object Blogger= "";
if (Blogger.ToString() != string.Empty)
{
    ....
}

in below code again shows same error . 在下面的代码再次显示相同的错误。

Most likely scm.ExecuteScalar() is bringing you a null value. 最有可能scm.ExecuteScalar()为您带来一个空值。 You need to test the value returned before using it: 您需要在使用之前测试返回的值:

var result = scm.ExecuteScalar();
MyLabel.Text = result == null ? '' : result.ToString();

scm.ExecuteScalar() is returning null, or scm is null, or lblLastNo is null. scm.ExecuteScalar()返回null,或者scm为null,或者lblLastNo为null。 That's the only reason you get the error 'Object reference not set ..'. 这是你得到错误'Object reference not set ..'的唯一原因。

ExecuteScalar return an Object type. ExecuteScalar返回Object类型。 This is why you have the same behavior on scm.ExecuteScalar().ToString(); 这就是你在scm.ExecuteScalar().ToString();上有相同行为的scm.ExecuteScalar().ToString(); or Blogger.ToString() . Blogger.ToString()

The object type default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows. ToString方法的对象类型默认实现返回Object类型的完全限定名称,如以下示例所示。

If this object is NULL, you will receive the error Object reference not set to an instance of an object. 如果此对象为NULL,您将收到错误Object reference not set to an instance of an object.

Your second case with : 你的第二个案例:

object blogger= "";
if (blogger.ToString() != string.Empty)
{
    ....
}

Should not throw an Exception but return a string that represents the object instance. 不应抛出异常但返回表示对象实例的字符串。 For example : "YourNameSpace.Blogger" 例如: "YourNameSpace.Blogger"

Please enclose with try catch block, so that you can handle runtime exceptions and its makes life easier to understand the problem. 请附上try catch块,以便您可以处理运行时异常,并使生活更容易理解问题。 and for if (Blogger.ToString() != string.Empty) this u can check for Null condition or if its string. 对于if (Blogger.ToString() != string.Empty)你可以检查Null条件或其字符串。 Then you can check for String.IsNullorEmpty 然后你可以检查String.IsNullorEmpty

  string str=blogger.toString();
    if (String.IsNullOrEmpty(str)) 
            //do something
   else 
     //do other part

String Is Null or EMpty 字符串为空或EMpty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM