简体   繁体   English

如何正确使用dr.GetString()?

[英]How to use dr.GetString() correctly?

I have a table which has 4 columns and I want to get only last column rows and show them in different labels 我有一个包含4列的表格,我只想获取最后一列的行,并以不同的标签显示它们

id   username     useraddress   location  comments
1    explename    expleaddre1   va        *NULL*
2    explename2   expleaddre2   ma        mycomments
3    explename3   expleaddre3   la        mycomments
4    explename4   expleaddre4   ka        mycomments


SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    lbluserid.Text = Convert.ToInt32(dr.GetString(0)).ToString();
    lblusername.Text = dr.GetString(1);
    lblusertitle.Text = dr.GetString(2);
    lst.Add(unt);
}
conn.Close();

and I am getting Unable to cast object of type 'System.Int32' to type 'System.String'. 并且我Unable to cast object of type 'System.Int32' to type 'System.String'.

I want to use datareader to get comments and show them (except NULL) in label1, label2, label3 ... 我想使用datareader来获取注释并在label1,label2,label3中显示它们(NULL除外)...

I tried to use dr.getstring() but it shows standard errors like outside of the .. , dbnull 我尝试使用dr.getstring(),但它显示标准错误,例如..,dbnull之外

Any help appreciated 任何帮助表示赞赏

When a field in your database contains null, the value that you find in your DataReader column is DBNull.Value 当数据库中的字段包含null时,在DataReader列中找到的值是DBNull.Value

The correct way to handle this value is the following 处理此值的正确方法如下

int ordinalPos = reader.GetOrdinal("Comments");
if(!reader.IsDBNull(ordinalPos))
{
    labelComment.Text = reader.GetString(ordinalPos);
}
else
{
    labelComment.Text = "No comments found!";
}

This could be transformed in an Extension method with some nice additions 这可以在扩展方法中进行一些附加的转换

public static class SqlDataReaderExtensions
{
    public static string GetString(this SqlDataReader reader, string colName, string defIfNull)
    {
       int ordinalPos = reader.GetOrdinal(colName);
       return (!reader.IsDBNull(ordinalPos) ? defIfNull : reader.GetString(ordinalPos));
    }
}

and called in a single line with this: 并在此一行中调用:

 labelComment.Text = reader.GetString("Comments", "No comments found");
using (SqlCommand command = new SqlCommand("SELECT * FROM YourTable", connection))
{
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
       string comments = reader.GetString(4);
       if (comments != null) 
           Console.WriteLine("Comments is {0}", comments);
       // Assign Text property of your labels..
    }
}

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

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