Computed columns in Gridview/DataTable in C#.

Hi all, sometime we need a field whose value is computed based on other fields. For example you have a datatable that has fields like “Id”, “Name”, “Salary”, “Tax”. Now you want one more field “NetSalary” that is (Salary – Tax). So our general approach is while assigning the value to datatable we calculate (Salary – Tax) and assign its value to NetSalary field. But you’ll have to do it for each row of datatable, also you’ll have to add some more lines of code to perform this calculation unnecessarily.

Here I am gonna explain one very good approach to do the task in optimized way. C# provides us so many things we just need to use them 🙂

        DataTable dt = new DataTable();
        dt.Columns.Add(“ID”);
        dt.Columns[“ID”].AutoIncrement = true;
        dt.Columns[“ID”].AutoIncrementSeed = 1;
        dt.Columns[“ID”].AutoIncrementStep = 1;
        dt.Columns.Add(“Name”);
        dt.Columns.Add(“Salary”, Type.GetType(“System.Double”));
        dt.Columns.Add(“Tax”, Type.GetType(“System.Double”));
        dt.Columns.Add(“NetSalary”, Type.GetType(“System.Double”));
        dt.Columns[“NetSalary”].Expression = “Salary – Tax”;

        DataRow dr = dt.NewRow();
        dr[“Name”] = “sunil”;
        dr[“Salary”] = 55000;
        dr[“Tax”] = 2500;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr[“Name”] = “maya”;
        dr[“Salary”] = 30000;
        dr[“Tax”] = 5200;
        dt.Rows.Add(dr);

        grid.DataSource = dt;
        grid.DataBind();

Advertisements

One thought on “Computed columns in Gridview/DataTable in C#.

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