-1

我有一个有 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();

我得到Unable to cast object of type 'System.Int32' to type 'System.String'.

我想使用 datareader 获取评论并在 label1、label2、label3 中显示它们(NULL 除外)...

我尝试使用 dr.getstring() 但它显示标准错误,如 .. 、 dbnull 之外

任何帮助表示赞赏

4

2 回答 2

4

When a field in your database contains null, the value that you find in your DataReader column is 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");
于 2013-05-17T22:29:56.617 回答
0
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..
    }
}
于 2013-05-17T22:14:54.260 回答