Thursday, July 16, 2015

Reading text file with multiple headings in c#

In this article i will describe how to read a text file having certain heading line by line and fill those in data table. As we know we all deal will different types of reports may be its transaction report,balance sheet,Income expense statements,etc.All these reports have certain fixed format .Most of the reports have headers for each category of transactions.

Q1 Expenses
Q1 % Total
Q2 Expenses
Q2 % Total
Q3 Expenses
Q3 % Total
Q4 Expenses
Q4 % Total
Advertising
Print
$10,000
11.60%
$12,000
12.40%
$10,000
11.60%
$12,000
12.40%
Radio
10,000
11.60%
11,000
11.30%
10,000
11.60%
11,000
11.30%
Television
25,000
29.10%
28,000
28.90%
25,000
29.10%
28,000
28.90%
Direct Mail
30,000
34.90%
32,000
33.00%
30,000
34.90%
32,000
33.00%
Point of Purchase
5,000
5.80%
6,000
6.20%
5,000
5.80%
6,000
6.20%
Co-op
5,000
5.80%
7,000
7.20%
5,000
5.80%
7,000
7.20%
Other
1,000
1.20%
1,000
1.00%
1,000
1.20%
1,000
1.00%
Totals
$86,000
12.00%
$97,000
13.10%
$86,000
12.00%
$97,000
13.10%
Sales Promotion
Trade Shows
$2,000
15.40%
$3,000
54.50%
$2,000
15.40%
$3,000
54.50%
Sales Force Promotion
10,000
76.90%
2,000
36.40%
10,000
76.90%
2,000
36.40%
Other
1,000
7.70%
500
9.10%
1,000
7.70%
500
9.10%
Totals
$13,000
1.80%
$5,500
0.70%
$13,000
1.80%
$5,500
0.70%

Now here is the code to fill data table with such type of data and show it in gridview. Later we can fill these data in database.
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ReadTextFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnRead_Click(object sender, EventArgs e) { gridbind(); } protected void gridbind() { DataTable dt = new DataTable(); string path = Server.MapPath("~/Marketing.txt"); if (!string.IsNullOrEmpty(path)) { string[] readText = File.ReadAllLines(path); List<string> rows = readText.ToList<string>(); DataColumn dc; string [] headers=rows[0].Split(new string[]{ "," },StringSplitOptions.None); foreach (string s in headers) { dc = new DataColumn(s, typeof(System.String)); dt.Columns.Add(dc); } rows.RemoveAt(0); rows.RemoveAll(u => !u.Contains("\"")); rows.RemoveAll(u => u.Contains("Totals")); DataRow dr; foreach (string s in rows) { string[] values = s.Split(new string[] { "\"" }, StringSplitOptions.None); dr = dt.NewRow(); for (int i = 0; i < headers.Count(); i++) { dr[i] = values[i].Replace(",", ""); } dt.Rows.Add(dr); } } grdData.DataSource = dt; grdData.DataBind(); } }

Tuesday, July 7, 2015

Serialization issue in ViewState Error "PublicKeyToken=null is not marked as serializable."

As we know Http is a stateless protocol .ie.the state is not maintained between various request to the server.Asp.net provides two types of state management techniques namely:Client Side ,Server Side. ViewState is one of the client Side State management.It is used to store the state of page between postbacks.Asp.net controls uses this property to maintain state between various postbacks.ViewState is stored as a hidden fields in page.
If you want to add a variable to the View State then we use following code
ViewState["Counter"]=count;
For retrieving data from ViewState we need to type cast it using type cast operator.
string count=(string)ViewState["Counter"];
ViewSate can be used to store any data type .For storing and retrieving primitive data type there is no problem.But when we want to store User Defined data types then we may end up in getting the error "class must be marked as Serializable or have TypeConvertor other than ReferenceConvertor to be put in ViewSate." or "PublicKeyToken=null' is not marked as serializable."
This is because our class is not Serializable . So an object of this type can’t be stored into ViewState.

public class Details { public int Id { get; set; } public string Name { get; set; } public string City { get; set; } public List<Details> GetDetails() { List<Details> Persons = new List<Details>(); Persons.Add(new Details { Id=1,Name= "Rajeev", City="Bangalore" }); Persons.Add(new Details { Id = 2, Name = "Raj Kumar", City = "Chennai" }); Persons.Add(new Details { Id = 3, Name = "Raj", City = "Mumbai" }); Persons.Add(new Details { Id = 4, Name = "Shiva", City = "Pune" }); Persons.Add(new Details { Id = 5, Name = "Lalit", City = "Ahmedabad" }); return Persons; } }
Details d = new Details(); ViewState["Data"] = d.GetDetails();
This will end up in getting error.To solve this issue add Serializable attribute to class definition .
[Serializable()] public class Details { }

Monday, July 6, 2015

Boot Strap Confirm Box In asp.net Web forms (Confirm Delete)

Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. In this example i will show how to use Bootstrap Confirm modal in asp.net.This is the most common Scenerio where we want to confirm before we delete any record.Here i will demonstrate how call confirm modal from within gridview link and if user confirms then only record will be deleted.
For the sake of simplicity i have used a class with some data .You can also use database to populate gridview.
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BootStrapConfirm { [Serializable()] public class Details { public int Id { get; set; } public string Name { get; set; } public string City { get; set; } public List<Details> GetDetails() { List<Details> Persons = new List<Details>(); Persons.Add(new Details { Id=1,Name= "Rajeev", City="Bangalore" }); Persons.Add(new Details { Id = 2, Name = "Raj Kumar", City = "Chennai" }); Persons.Add(new Details { Id = 3, Name = "Raj", City = "Mumbai" }); Persons.Add(new Details { Id = 4, Name = "Shiva", City = "Pune" }); Persons.Add(new Details { Id = 5, Name = "Lalit", City = "Ahmedabad" }); return Persons; } } }
Now we will create a webform ConfirmDemo.aspx.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ConfirmDemo.aspx.cs" Inherits="BootStrapConfirm.ConfirmDemo" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Confirm Demo</title> <script src="js/jquery-1.10.2.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap-dialog.min.js"></script> <link href="css/bootstrap-dialog.min.css" rel="stylesheet" /> <link href="css/bootstrap.min.css" rel="stylesheet" /> <style> .row1 { padding: 4px 30px 4px 6px; border-bottom: 1px solid #b3b3b3; } .header { background: #646464; color: #d1d1d1; text-align: center; font-weight: bold; padding: 4px 30px 4px 6px; border-bottom: 1px solid #b3b3b3; } </style> </head> <body> <form id="form1" runat="server"> <h2> Confirm Demo Using Bootstrap Dialog </h2> <div class="container"> <asp:GridView ID="grdDemo" runat="server" AutoGenerateColumns="false" RowStyle-CssClass="row1" HeaderStyle-CssClass="header" OnRowCommand="grdDemo_RowCommand" OnRowDeleting="grdDemo_RowDeleting"> <Columns> <asp:TemplateField HeaderText="Id"> <ItemTemplate> <asp:Label ID="lblId" runat="server" Text='<%#Eval("Id") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="City"> <ItemTemplate> <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Action"> <ItemTemplate> <asp:LinkButton ID="lnkDelete" runat="server" CssClass="" OnClientClick='<%# string.Concat("if(!popup(this.id",",",Eval("ID"),",\"",Eval("Name"),"\"))return false; ") %>' Text="Delete" CommandArgument='<%# Eval("Id") %>' CommandName="Delete" ></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> <script> function popup(lnk, id, Name) { BootstrapDialog.confirm({ title: 'WARNING', message: 'Do You Want To Delete <b>'+Name+'</b>', type: BootstrapDialog.TYPE_WARNING, // <-- Default value is BootstrapDialog.TYPE_PRIMARY closable: true, // <-- Default value is false draggable: true, // <-- Default value is false btnCancelLabel: 'Cancel', // <-- Default value is 'Cancel', btnOKLabel: 'Ok', // <-- Default value is 'OK', btnOKClass: 'btn-warning', // <-- If you didn't specify it, dialog type will be used, callback: function (result) { // result will be true if button was click, while it will be false if users close the dialog directly. if (result) { javascript: __doPostBack('grdDemo$ctl02$lnkDelete', ''); } else { BootstrapDialog.closeAll(); } } }); } </script> </form> </body> </html>
Here is the code behind for the same.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace BootStrapConfirm { public partial class ConfirmDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) gridbind(); } protected void grdDemo_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Delete") { LinkButton lnkView = (LinkButton)e.CommandSource; string dealId = lnkView.CommandArgument; List<Details> data = (List<Details>)ViewState["Data"]; data.RemoveAll(d => d.Id == Convert.ToInt32(dealId)); ViewState["Data"] = data; gridbind(); System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "BootstrapDialog.alert('Record Deleted Successfully.');", true); //data. } } protected void gridbind() { if (ViewState["Data"] != null) { } else { Details d = new Details(); ViewState["Data"] = d.GetDetails(); } grdDemo.DataSource = (List<Details>)ViewState["Data"]; grdDemo.DataBind(); } protected void grdDemo_RowDeleting(object sender, GridViewDeleteEventArgs e) { } } }

Thursday, July 2, 2015

Render Gridview Header as thead and Footer as tfoot

Asp.net GridView control is one of the data binding control most often used .But it has one problem that when rendering on browser it generate all rows including header and footer in <tbody >section rather than creating seperate <thead> and <tfoot>.This is how gridview is rendered as html.Note that even header is generated as row in tbody section.

<table  id="MainContent_grdNormal" >
<tbody>
<tr class="header content-wrapper" >
<th scope="col">EmpId</th>
<th scope="col">EmpName</th>
<th scope="col">City</th>
</tr>
<tr>
<td>L1Z 5F4</td>
<td>Nathaniel</td>
<td>Ilbono</td>
</tr>
<tr >
<td>B7F 4U4</td>
<td>Ross</td>
<td>Dover</td>
</tr>
<tr>
<td>R9C 1T9</td>
<td>Patrick</td>
<td>Edam</td>
</tr>
</tbody>
</table>

Now to force a gridview to render <thead> and <tfoot>,we need to add 3 lines of code after grid is binded. Below is the code to achieve the same.
using System;

using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace GridHeaders { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { gridbind(); AddHeaders(); } } protected void AddHeaders() { if (grdNormal.Rows.Count > 0) { //This replaces <td> with <th> grdNormal.UseAccessibleHeader = true; //This will add the <thead> and <tbody> elements grdNormal.HeaderRow.TableSection = TableRowSection.TableHeader; //This adds the <tfoot> element. Remove if you don't have a footer row grdNormal.FooterRow.TableSection = TableRowSection.TableFooter; } } protected void gridbind() { DataTable dt = new DataTable(); dt.Columns.Add("EmpId", typeof(string)); dt.Columns.Add("EmpName", typeof(string)); dt.Columns.Add("City", typeof(string)); DataRow dr1= dt.NewRow(); dr1[0] = "L1Z 5F4"; dr1[1] = "Nathaniel"; dr1[2] = "Ilbono"; dt.Rows.Add(dr1); DataRow dr2 = dt.NewRow(); dr2[0] = "B7F 4U4"; dr2[1] = "Ross"; dr2[2] = "Dover"; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3[0] = "R9C 1T9"; dr3[1] = "Patrick"; dr3[2] = "Edam"; dt.Rows.Add(dr3); grdNormal.DataSource = dt; grdNormal.DataBind(); } } }
Note:-Call AddHeaders() method after binding gridview otherwise you will get The table must contain row sections in order of header, body, then footer error

Convert Gridview Rows To Column (Transpose Gridview)


In this article i will show how to convert Gridview Rows to Column in C#.Lets begin by adding 2 GridViews to a page and a button.Now we need to create a DataTable .For Simplicity i am adding data to datatable in gridbind Method and populating the gridview with that data manually you can fill datatable with database.Store this datatable in ViewState.Now we call this method in page load.
For converting GridView Row to column i have created a method Transpose.Now what we have to do in transpose method.
1)We need to create a new datatable newdt.Retrieve the old datatable from viewstate .The number of columns in new datatable newdt will be equal to number of rows in dt.
2)Add Columns to the new datatable newdt(Column Name is passed as blank ).
3) Create a datarow dr .Iterate through all columns and add for each column value get all the values of the rows in old datatable dt and store it in dr.
4)Add Datarow dr to newdt. Now Add Click event for the button and call the transpose method.

Here is the code


<style type="text/css">
        .header {
            padding:5px;background-color:#7ac0da; font-weight:bold;
        }
      .header content-wrapper table tr  td {
            border:dotted 1px solid !important;
        }
    </style>
    <br />
<div style="text-align: center;">
<asp:gridview alternatingrowstyle-backcolor="#ccffff" bordercolor="Gray" gridlines="Both" headerstyle-backcolor="#7ac0da" headerstyle-bordercolor="Gray" headerstyle-cssclass="header content-wrapper" id="grdNormal" runat="server">
    </asp:gridview>
    </div>
<div style="text-align: center;">
<asp:linkbutton id="lnkConvert" onclick="lnkConvert_Click" runat="server"><img src="Images/down.png" style="width: 50px;" /></asp:linkbutton>
    </div>
<div style="text-align: center;">
<asp:gridview bordercolor="Gray" gridlines="Both" headerstyle-bordercolor="Gray" id="grdTranspose" onrowcreated="grdTranspose_RowCreated" runat="server" showheader="false">
    </asp:gridview>
    </div>
</div>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace GridTranspose { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { grdibind(); } } protected void grdibind() { DataTable dt = new DataTable(); dt.Columns.Add("EmpId", typeof(string)); dt.Columns.Add("EmpName", typeof(string)); dt.Columns.Add("City", typeof(string)); DataRow dr1= dt.NewRow(); dr1[0] = "L1Z 5F4"; dr1[1] = "Nathaniel"; dr1[2] = "Ilbono"; dt.Rows.Add(dr1); DataRow dr2 = dt.NewRow(); dr2[0] = "B7F 4U4"; dr2[1] = "Ross"; dr2[2] = "Dover"; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3[0] = "R9C 1T9"; dr3[1] = "Patrick"; dr3[2] = "Edam"; dt.Rows.Add(dr3); ViewState["GridData"] = dt; grdNormal.DataSource = dt; grdNormal.DataBind(); } protected void lnkConvert_Click(object sender, EventArgs e) { Transpose(); } protected void Transpose() { DataTable dt = (DataTable)ViewState["GridData"]; DataTable newdt = new DataTable(); //Create New Columns( count of columns will be equal to number of rows including header for (int i = 0; i <= dt.Rows.Count; i++) { //Column Name string is not specified because column name will come in rows at start newdt.Columns.Add(""); } //Now Iterate through old datatable and fill new datatable //Create a new row in New DataTable for (int k = 0; k < dt.Columns.Count; k++) { DataRow newdr = newdt.NewRow(); //Assign first column Value in NewDatatable with column name of old table newdr[0] = dt.Columns[k].ColumnName.ToString(); for (int j = 0; j < dt.Rows.Count; j++) { newdr[j + 1] = dt.Rows[j][k].ToString(); } newdt.Rows.Add(newdr); } grdTranspose.DataSource = newdt; grdTranspose.DataBind(); } protected void grdTranspose_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[0].CssClass = "header"; } } } }
Note:-Actually here we are transposing data table and binding to gridview.