Few random development Tips-N-Tricks-2

Two interesting things about DataTable —
(1) DataTable.Expression and (2) DataTable.LoadDataRow
The first one I use, —  to add a new Column to a DataTable, which will be populated with an already existing column’s value, when the column gets created. Here’s an example

public DataTable AddColumnWithExistingValue()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("person_id");
        dt.Columns.Add("person_name");
        dt.Columns.Add("person_city");
        dt.Columns.Add("person_zipcode");
        dt.Columns.Add("person_city_copy");
        dt = GetPersonDetails(); //Populate the DataTable from any data source
        //Now add another new column "person_city_copy" which will contain the same value as old "person_city"
        dt.Columns["person_city_copy"].Expression = "person_city";
        dt.AcceptChanges();
        return dt;
    }


Second one helped me populate a DataTable from generic List Array

public class Person
    {
        public int person_id { get; set; }
        public string person_name { get; set; }
        public string person_city { get; set; }
        public string person_zipcode { get; set; }
    }
    public DataTable getPersons3(DataTable dt)
    {
        //Fill a DataTable from List array
        List<Person> _Persons = getPersons();
        object[] h1 = new object[4];
        dt.BeginLoadData();
        foreach (Person item in _Persons)
        {
            h1[0] = item.person_id;
            h1[1] = item.person_name;
            h1[2] = item.person_city;
            h1[3] = item.person_zipcode;
            dt.LoadDataRow(h1, true);
        }
        dt.EndLoadData();
        return dt;
    }
    public List<Person> getPersons()
    {
        List<Person> _Persons = new List<Person>();
        _Persons.Add(new Person { person_id = 1, person_name = "a1", person_city = "c1", person_zipcode = "11111" });
        _Persons.Add(new Person { person_id = 2, person_name = "a2", person_city = "c2", person_zipcode = "22222" });
        _Persons.Add(new Person { person_id = 3, person_name = "a3", person_city = "c3", person_zipcode = "33333" });
        _Persons.Add(new Person { person_id = 4, person_name = "a4", person_city = "c4", person_zipcode = "44444" });
        return _Persons;
    }

Hope this helps. Thanks for reading.

Advertisements
This entry was posted in Tips-n-Tricks. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s