4

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

Community
  • 1
  • 1
IAbstract
  • 19,551
  • 15
  • 98
  • 146

2 Answers2

4

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 });
this. __curious_geek
  • 42,787
  • 22
  • 113
  • 137
1

I don't know why that is happening, but have tried to use a binding source?

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

and then

dgrid_Main.DataSource = binding1
Steve Mallory
  • 4,245
  • 1
  • 28
  • 31