Displaying Data from an Array

Sunday, March 25, 2012
Most of you are aware about the binding of data using a datasource. In most of the cases you might used a DataTable, DataSet or a DataReader objects as a datasource, and it works pretty good. No issues...

Now suppose you have a list or say an array of a string that you want to bind with a DataGridView. Fairly simple.

Refer the code snippet

namespace BlogSamples.ArrayBinding
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] users = new string[] { "Abhinav", "Vivek", "Avinash", "Sunny", "Rajiv" };
            dataGridView1.DataSource = users;
        }
    }
}

So far so good!!

And the result is...........


Surprised? What happened to my user name which is the elements of the users array? Why it is showing the length of each member of the array members? OK, let me explain.

When using an array as the source of data for a DataGridView control, the grid looks for the first public property of the object within the array and displays this value rather than the string value. The first (any only) public property of string is Length, so that is what is displayed. 


Now the solution of the problem can be solved by a wrapper class that will encapsulate the string value in a class.
  
     private class Item   {
            private string _Tvalue;
            public Item(string Text)
            {
                _Tvalue = Text;
            }

            public string Text
            {
                get { return _Tvalue; }
            }
        }
And create an array of Item class. Fill it with member elements like below.

            Item[] users = new Item[5];
            users[0] = new Item("Abhinav");
            users[1] = new Item("Vivek");
            users[2] = new Item("Avinash");
            users[3] = new Item("Sunny");
            users[4] = new Item("Rajiv");

            dataGridView1.DataSource = users;
And the result is

The Item class contains only one public property "Text" so the DataGridView binds with the Text property.

Conclusion:
From the above exercise, we learned about the data binding of an array of the string type. So next time when you will face the same issue, just remember about the first public property of the object.

Comments are welcome!!

Copyright @ 2013 C # Lab. Designed by Templateism | MyBloggerLab

About Metro

Follow us on Facebook