Search code examples
c#datagridviewdatasourceilist

Why String.Length is returned instead of actual value in DataSource


I have this code which builds an IList<string>:

IList<string> databases;

using (MySqlConnection _conn = Session.Connection)
using (MySqlCommand _cmd = _conn.CreateCommand("SHOW databases"))
{
    _cmd.Connection.Open ( );
    var _dr = _cmd.ExecuteReader();

    databases = new List<string> ( _dr.SelectFromReader ( reader =>
        reader[ 0 ] is DBNull ? null : reader[ 0 ].ToString ( ) ) );

    _cmd.Connection.Close ( );
}

dgrid_Main.DataSource = databases;

Follow the workings of extension method SelectFromReader here.

The question is, how come dgrid_Main is displaying the length of each database ...
display length of database names
... rather than the name? I ran this test:

foreach (string db in databases)
{
    //  winform treeview control
    trv_ServerObjects.Nodes.Add ( db );
}

... I get the following result:
display database name


Solution

  • Because the DataSource property on dgrid_Main will bind each public property of the object in collection and not the object it self. And Length is one public-property of the string object.

    When you actually iterate through the IList you get the list of database-names.

    Try this..

    dgrid_Main.DataSource = databases.ToList().Select(db => new { db });