Friday, August 24, 2012

Calculated Columns in .NET Data Tables (C#)

Recently I had a requirement to add Calculated Columns to Data Table. For an example I’m Only providing Amount and Quantity. Then discount will be calculated automatically.

String Discount = ".1";
DataTable workTable = new DataTable("Customers");

DataColumn workCol = workTable.Columns.Add("ID", typeof(Int32));
workTable.Columns.Add("UnitPrice", typeof(Double));
workTable.Columns.Add("Quantity", typeof(Int16));
workTable.Columns.Add("Total", typeof(Double));
workTable.Columns.Add("Discount", typeof(Double));

workTable.Columns["Total"].Expression = "UnitPrice*Quantity";
workTable.Columns["Discount"].Expression = String.Format("Total*{0}",Discount);
Later you can bind the Data Table to a Grid View if you need.
dataGridView1.DataSource = workTable;
dataGridView1.Update();

Special Note:


But my requirement was to update the Column Expression dynamically in the runtime. For an example Discount will be change according to the total amount. Therefore this method can not cater that requirement since  expression is fixed with the discount.


Thus I update the Column Expression in   dataGridView1_DataBindingComplete and invalidate the control for force data panting.

Double RunningSum = 0;
String ValDiscount = "50";
workTable.Columns["ValueDis"].Expression = String.Format("{0}/{1}*Total", ValDiscount, RunningSum.ToString());
dataGridView1.Invalidate();

Wednesday, August 22, 2012

The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again

This error occurred to me when I introduce ElevatedPrivilages block to the project.

SPSecurity.RunWithElevatedPrivileges(delegate()
{…}
I refreshed the page and still I got the error. Then I found that I missed the
web.AllowUnsafeUpdates = true;
in the code.

Wednesday, August 15, 2012

What is the Different Between Eval() And Bind() in ASP.NET

Eval() is a one way binding mechanism therefore it can be used as a ReadOnly expression.

But Bind() works as a two way mechanism. therefore changes are getting reflect in the data source also.

Dynamically set Label BackColor (Control Back Color) in ASP.NET Grid

I engaged with fining a method of dynamically change control’s background color in a ASP.NET grid based on data in the data source.

I used the following code for get the task done.

<asp:TemplateField HeaderText="Color 01">
<
ItemTemplate>
<
asp:Label ID="lblColor1" runat="server"
BackColor='<%# System.Drawing.ColorTranslator.FromHtml((String)Eval("Color1")) %>' Text='<%# Bind("Color1") %>' >
       </asp:Label>
</
ItemTemplate>
</
asp:TemplateField>