DBReader提供字符串长度而不是字符串

时间:2014-06-06 14:44:15

标签: c#

目前我的问题是,当我运行代码时,它会显示一个数据网格,其中包含Forename的length而不是Forename本身。任何人都有任何线索,看起来很傻。

List<string> NameList = new List<string>();
string connectionString = "Server = localhost; Database = TestDb; Trusted_Connection = True;";
try
    {
    IDbConnection dbcon;
    using (dbcon = new SqlConnection(connectionString))
    {
        dbcon.Open();
        using (IDbCommand dbcmd = dbcon.CreateCommand())
        {
            string sql = "Select * from people";
            dbcmd.CommandText = sql;
            using (IDataReader reader = dbcmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    string FirstName = (string) reader["ForeName"];
                    NameList.Add(FirstName);
                }
                DataGrid1.ItemsSource = NameList.ToList();
                reader.Close();
                dbcon.Close();
            }
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

1 个答案:

答案 0 :(得分:2)

将您的List<string>更改为以下内容

IList<string> NameList = new List<string>();
DataGrid1.DataSource = NameList.Select(s => new 
                       { 
                           Value = s 
                       }).ToList();

这些方面的东西不会伤害到尝试