Tuesday, July 21, 2015

Event Calender in Asp.net using calender Control

In this article i will show how to create a basic Event Calendar using Asp.net.Here i will use the ASP.net Calender control to show events.Here i will be making use of two events of calendar control(DayRender,SelectionChanged).
For showing events in the calender i will be adding a link in DayRender method but in doing so we will be able to get that links click in code behind.The reason is because the DayRender event is raised while the Calendar control is being rendered, you cannot add a control that can also raise an event, such as LinkButton. You can only add static controls, such as LiteralControl, Label, Image, and HyperLink.
There is a workaround to get value in code behind.For this i will add a static link button and make it hidden in the page and this button will handle all the events that are raised by the events that i will add .
Now in the DayRender event i will add a hyperlink control for all those dates which will have an event and in navigate url of hyperlink i will call dopostback to hidden link button with argument value.Here is the code for the same.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EventCalender.aspx.cs" Inherits="EventCalender" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .modalBackground { background-color: Black; filter: alpha(opacity=90); opacity: 0.8; } .modalPopup { background-color: #FFFFFF; border-width: 3px; border-style: solid; padding-top: 10px; padding-left: 10px; width: 500px; height: 300px; overflow-y:scroll; vertical-align:top; } .modalPopup1 { background-color: #FFFFFF; border-width: 3px; border-style: solid; padding-top: 10px; padding-left: 10px; width: 300px; height: 200px;overflow-y:scroll;vertical-align:top; } /* Set the Style for parent CSS Class of Calendar control Parent [CssClass] = myCalendar */ .myCalendar { background-color: #efefef; width: 200px; } /* Common style declaration for hyper linked text */ .myCalendar a { text-decoration: none; } /* Styles declaration for top title [TitleStyle] [CssClass] = myCalendarTitle */ .myCalendar .myCalendarTitle { font-weight: bold; } /* Styles declaration for date cells [DayStyle] [CssClass] = myCalendarDay */ .myCalendar td.myCalendarDay { border: solid 2px #fff; border-left: 0; border-top: 0; } /* Styles declaration for next/previous month links [NextPrevStyle] [CssClass] = myCalendarNextPrev */ .myCalendar .myCalendarNextPrev { text-align: center; } /* Styles declaration for Week/Month selector links cells [SelectorStyle] [CssClass] = myCalendarSelector */ .myCalendar td.myCalendarSelector { background-color: #dddddd; } .myCalendar .myCalendarDay a, .myCalendar .myCalendarSelector a, .myCalendar .myCalendarNextPrev a { display: block ; line-height: 15px; } .myCalendarDay noti_Container a { display: block ; line-height: 15px; } .myCalendar .myCalendarDay a:hover, .myCalendar .myCalendarSelector a:hover { background-color: #cccccc; } .myCalendar .myCalendarNextPrev a:hover { background-color: #fff; } #noti_Container { position:relative; width:16px; height:16px; float:right; top:-23px; } .noti_bubble { /*position:absolute;*/ top: -6px; right:-6px; padding:1px 2px 1px 2px; background-color:red; color:white; font-weight:bold; font-size:0.55em; border-radius:30px; box-shadow:1px 1px 1px gray; } .button-link { padding: 2px 5px; background: #4479BA; color: #FFF; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; border: solid 1px #20538D; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2); -webkit-transition-duration: 0.2s; -moz-transition-duration: 0.2s; transition-duration: 0.2s; -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; } .button-link:hover { background: #356094; border: solid 1px #2A4E77; text-decoration: none; } </style> </head> <body> <form id="form1" runat="server"> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager> <asp:Calendar ID="Calendar1" runat="server" DayNameFormat="FirstLetter" Font-Names="Arial" Font-Size="11px" NextMonthText="»" PrevMonthText="«" SelectMonthText="»" SelectWeekText="›" CssClass="myCalendar" BorderStyle="None" Width="350" Height="300" CellPadding="1" OnSelectionChanged="Calendar1_SelectionChanged" OnVisibleMonthChanged="Calendar1_VisibleMonthChanged" OnDayRender="Calendar1_DayRender"> <OtherMonthDayStyle ForeColor="Gray" /> <DayStyle CssClass="myCalendarDay" /> <SelectedDayStyle Font-Bold="True" Font-Size="12px" /> <SelectorStyle CssClass="myCalendarSelector" /> <NextPrevStyle CssClass="myCalendarNextPrev" /> <TitleStyle CssClass="myCalendarTitle" /> </asp:Calendar> <asp:LinkButton ID="lnkButton" runat="server" CssClass="hide" OnClick="lnkButton_Click"></asp:LinkButton> <asp:ModalPopupExtender ID="Calendar1_ModalPopupExtender" BackgroundCssClass="modalBackground" PopupControlID="Panel1" runat="server" DynamicServicePath="" Enabled="True" TargetControlID="hdnlink"></asp:ModalPopupExtender> <asp:LinkButton ID="hdnlink" style="display:none;" runat="server" OnClick="hdnlink_Click">Submit</asp:LinkButton> <br /> <asp:ModalPopupExtender ID="ModalPopupExtender1" BackgroundCssClass="modalBackground" PopupControlID="Panel2" runat="server" DynamicServicePath="" Enabled="True" TargetControlID="hdnlnk2"></asp:ModalPopupExtender> <asp:LinkButton ID="hdnlnk2" style="display:none;" runat="server" OnClick="hdnlnk2_Click">Submit</asp:LinkButton> <br /> <asp:ModalPopupExtender ID="ModalPopupExtender2" BackgroundCssClass="modalBackground" PopupControlID="Panel3" runat="server" DynamicServicePath="" Enabled="True" TargetControlID="hdnlnk3"></asp:ModalPopupExtender> <asp:LinkButton ID="hdnlnk3" style="display:none;" runat="server" OnClick="hdnlnk3_Click">Submit</asp:LinkButton> <br /> <asp:Panel ID="Panel3" runat="server" CssClass="modalPopup" align="center" style = "display:none" > <table style="width:95%;"> <tr> <td></td> <td> <asp:LinkButton ID="LinkButton2" runat="server" Font-Size="Small" Style="float:right;" >Close</asp:LinkButton></td> </tr> </table> <asp:GridView ID="GridView2" runat="server" Width="95%" CellPadding="4" AutoGenerateColumns="false" ForeColor="#333333" GridLines="None" OnRowCommand="GridView2_RowCommand"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> <Columns> <asp:TemplateField HeaderText="Category" ShowHeader="true"> <ItemTemplate> <asp:LinkButton ID="lnkCategory" runat="server" CausesValidation="False" Text='<%# Eval("Category") %>' CommandName="Category" CommandArgument='<%#Eval("Category") + ";" +Eval("Date")%>'></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </asp:Panel> <asp:Panel ID="Panel2" runat="server" CssClass="modalPopup" align="center" style = "display:none" > <table style="width:95%;"> <tr> <td></td> <td> <asp:LinkButton ID="LinkButton1" runat="server" Font-Size="Small" Style="float:right;" >Close</asp:LinkButton></td> </tr> </table> <asp:GridView ID="GridView1" runat="server" Width="95%" Height="250" ShowHeader="false" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="false" GridLines="None"> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> <EditRowStyle BackColor="#999999" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#E9E7E2" /> <SortedAscendingHeaderStyle BackColor="#506C8C" /> <SortedDescendingCellStyle BackColor="#FFFDF8" /> <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> <Columns> <asp:TemplateField ShowHeader="false"> <ItemTemplate> <div style="color:White;background-color:#5D7B9D;font-weight:bold;padding:5px;" > <%# Eval("Event Name") %> <div style="float:right;"> <%# Eval("Date") %> </div> </div> <div> <%# Eval("Description") %> </div> <div> <%# Eval("Category") %> </div> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </asp:Panel> <asp:Panel ID="Panel1" runat="server" CssClass="modalPopup1" align="center" style = "display:none" > <table> <tr> <td></td> <td> <asp:LinkButton ID="lnkCancel" runat="server" Font-Size="Small" Style="float:right;" >Close</asp:LinkButton></td> </tr> <tr> <td> Event Name </td> <td> <asp:TextBox ID="txtEventName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Location </td> <td> <asp:TextBox ID="txtLocation" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Category </td> <td> <asp:DropDownList ID="ddlCategory" runat="server"> <asp:ListItem Text="Concerts" Value="Concerts"></asp:ListItem> <asp:ListItem Text="Festivals" Value="Festivals"></asp:ListItem> <asp:ListItem Text="Kids & Family" Value="Kids & Family"></asp:ListItem> <asp:ListItem Text="Performing Arts" Value="Performing Arts"></asp:ListItem> <asp:ListItem Text="Food" Value="Food"></asp:ListItem> <asp:ListItem Text="Sports" Value="Sports"></asp:ListItem> <asp:ListItem Text="Conferences" Value="Conferences"></asp:ListItem> <asp:ListItem Text="Movies" Value="Movies"></asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> Description </td> <td> <asp:TextBox ID="txtDesc" runat="server" TextMode="MultiLine"></asp:TextBox> </td> </tr> <tr> <td></td> <td> <asp:LinkButton ID="lnkSubmit" runat="server" CssClass="button-link" OnClick="lnkSubmit_Click">Submit</asp:LinkButton><br /> </td> </tr> </table> </asp:Panel> </form> </body> </html>

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; using System.Web.UI.HtmlControls; public partial class EventCalender : System.Web.UI.Page { private LinkButton lb ; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { gridbind(); } } protected void gridbind() { if (Session["Events"] != null) { DataTable dt = (DataTable)Session["Events"]; GridView1.DataSource = dt; GridView1.DataBind(); } } protected void CategoryGridbind(DataTable dt) { GridView2.DataSource = dt; GridView2.DataBind(); } protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) { if (Session["Events"] != null) { DataTable dt = (DataTable)Session["Events"]; var count = (from events in dt.AsEnumerable() where events.Field("Date").Contains(e.Day.Date.ToShortDateString()) select events).Count(); if (Convert.ToInt32(count)>0) { var span = new HtmlGenericControl("div"); HyperLink lb = new HyperLink(); lb.Text = count.ToString(); lb.CssClass = "noti_bubble"; lb.NavigateUrl = Page.ClientScript.GetPostBackClientHyperlink(lnkButton, e.Day.Date.ToShortDateString(), true); span.Controls.Add(lb); span.ID = "noti_Container"; e.Cell.Controls.Add(span); } } } protected void lnkButton_Click(object sender, EventArgs e) { string date = Request.Form["__EVENTARGUMENT"].ToString(); if (Session["Events"] != null) { DataTable dt = (DataTable)Session["Events"]; DataTable catdt = (from events in dt.AsEnumerable() where events.Field("Date").Contains(date) group events by events.Field("Category") into groups select groups.First()).CopyToDataTable(); CategoryGridbind(catdt); } hdnlnk3_Click(null, null); } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { string date = Calendar1.SelectedDate.ToShortDateString(); hdnlink_Click(null, null); } protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e) { Calendar1_ModalPopupExtender.Hide(); } protected void hdnlink_Click(object sender, EventArgs e) { Calendar1_ModalPopupExtender.Show(); } protected void hdnlnk2_Click(object sender, EventArgs e) { ModalPopupExtender1.Show(); } protected void hdnlnk3_Click(object sender, EventArgs e) { ModalPopupExtender2.Show(); } protected void lnkSubmit_Click(object sender, EventArgs e) { if (Session["Events"] != null) { DataTable dt = (DataTable)Session["Events"]; DataRow dr=dt.NewRow(); dr[0]=txtEventName.Text.Trim(); dr[1]=txtLocation.Text.Trim(); dr[2]=Calendar1.SelectedDate.ToShortDateString(); dr[3] = txtDesc.Text.Trim(); dr[4] = ddlCategory.SelectedItem.Value.ToString(); dt.Rows.Add(dr); Session["Events"] = dt; } else { DataTable events = new DataTable(); DataColumn dc1 = new DataColumn("Event Name", typeof(String)); DataColumn dc2 = new DataColumn("Location", typeof(String)); DataColumn dc3 = new DataColumn("Date", typeof(String)); DataColumn dc4 = new DataColumn("Description", typeof(String)); DataColumn dc5 = new DataColumn("Category", typeof(String)); events.Columns.Add(dc1); events.Columns.Add(dc2); events.Columns.Add(dc3); events.Columns.Add(dc4); events.Columns.Add(dc5); DataRow dr = events.NewRow(); dr[0] = txtEventName.Text.Trim(); dr[1] = txtLocation.Text.Trim(); dr[2] = Calendar1.SelectedDate.ToShortDateString(); dr[3] = txtDesc.Text.Trim(); dr[4] = ddlCategory.SelectedItem.Value.ToString(); events.Rows.Add(dr); Session["Events"] = events; } txtDesc.Text = string.Empty; txtEventName.Text = string.Empty; txtLocation.Text = string.Empty; } protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Category") { if (Session["Events"] != null) { DataTable dt = (DataTable)Session["Events"]; string[] arg = new string[2]; arg = e.CommandArgument.ToString().Split(';'); DataTable eventscategorywise = (from events in dt.AsEnumerable() where events.Field("Date").Contains(arg[1]) && events.Field("Category")==arg[0].ToString() select events).CopyToDataTable(); GridView1.DataSource = eventscategorywise; GridView1.DataBind(); hdnlnk2_Click(null, null); } } } }

Friday, July 17, 2015

Add Identity column to a data table containing data

In this post i will describe how to add an identity column to an already existing data table which contains data.Suppose we are having a data table that is returned by executing some query,now instead of modifying the query we can add a new column to the data table and make it as identity column.Here is the code to do so.
SqlDataAdapter da=new SqlDataAdapter(cmd,conn);
Dataset ds=new Dataset();
da.Fill(ds);
DataTable dt = ds.Tables[0]; //Now we have Data Table DataColumn dc = new DataColumn("ID"); dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; ddt.Columns.Add(dc);
dc.SetOrdinal(0); //Set values for existing rows for (int i = 0; i <= dt.Rows.Count - 1; i++) 
{ dt.Rows(i).Item("ID") = i + 1; }

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(); } }