GridView Inside GridView




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataRelation.aspx.cs"
Inherits="DataRelation" %>


<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView2"
DataSource='<%#((DataRowView)Container.DataItem).CreateChildView("ParentChild") %>'
runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Dept"
HeaderText="Department" />
<asp:BoundField DataField="name"
HeaderText="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DataRelation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

GridView1.DataSource = CreateDS().Tables["Company"];
GridView1.DataBind();

}

}
private DataSet CreateDS()
{
DataSet ds;
if (Session["DataList_ParentChild"] == null)
{
ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));
dt.Columns.Add(new DataColumn("Address", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Dept", typeof(string)));
for (int i = 1; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company " + i;
dr[2] = "Address " + i;
dr[3] = "Manager name";
dr[4] = "Adminstration";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;

dt = new DataTable("Employees");
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Dept", typeof(string)));
for (int i = 1; i < 10; i++)
{
int imax = 0;
if (i % 2 == 0) imax = 5;
else imax = 4;
for (int y = 2; y < imax; y++) //3 emplyees for each company
{
dr = dt.NewRow();
dr[0] = y + i * 5;
dr[1] = i;
dr[2] = "Employee # " + dr[0];
dr[3] = "Dept # " + (y + i);
dt.Rows.Add(dr);
}
}
DataColumn[] Child_PKColumns = new DataColumn[1];
Child_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Child_PKColumns;
ds.Tables.Add(dt);
DataColumn[] Child_FKColumns = new DataColumn[1];
Child_FKColumns[0] = dt.Columns["CompanyID"];




ds.Relations.Add("ParentChild", Parent_PKColumns, Child_FKColumns);
Session["DataList_ParentChild"] = ds;
}
else
{
ds = (DataSet)Session["DataList_ParentChild"];
}
return ds;

}
}

JavaScript Tips

let us supposed that you have a textbox is clicked, you need the text that says "Enter your search
here" to dissappear. This is the javascript for this?.
<asp:TextBox ID="TextBox1" runat="server" Text="Serch Here"
onkeydown="if (this.value == 'Serch Here') this.value = '';"
onclick="this.value=''"></asp:TextBox>

CheckBox OnClick Hide/Show HTML Table

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HideShow.aspx.cs"
Inherits="HideShow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

<script type="text/javascript">
function ShowHide(obj)
               {
                   if(!obj.checked) {
                     document.getElementById('tbl_QuestionTags_Software').style.display = 'none';
                     document.getElementById('tbl_QuestionTags_Software').style.visibility="hidden";
                     }
                    else {
                    document.getElementById('tbl_QuestionTags_Software').style.display = '';
                    document.getElementById('tbl_QuestionTags_Software').style.visibility ="visible";
                   }
               }


</script>

<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
   <div>
       <asp:CheckBox ID="chk_QuestionTags_Software" runat="server" CssClass="text" Text="Software"
           onclick="ShowHide(chk_QuestionTags_Software)" />
       <table id="tbl_QuestionTags_Software" border="1" bordercolor="red" cellpadding="0"
           cellspacing="0" style="width: 100%">
           <tr>
               <td>
                   Test1</td>
               <td>
                   Test1</td>
               <td>
                   Test1</td>
               <td>
                   Test1</td>
               <td>
                   Test1</td>
           </tr>
       </table>
   </div>
</form>
</body>
</html>

Master Detail Using GridView and DetailsView

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewInsideGridView.aspx.cs"
   Inherits="GridViewInsideGridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True"
               DataKeyNames="Id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
               <Columns>
                   <asp:BoundField DataField="Id" />
                   <asp:BoundField DataField="Name" />
               </Columns>
           </asp:GridView>
        
           <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" Height="50px"
               Width="176px">
               <Fields>
                   <asp:BoundField DataField="Id" />
                   <asp:BoundField DataField="Qul" />
               </Fields>
           </asp:DetailsView>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridViewInsideGridView : System.Web.UI.Page
{
    DataSet ds;
    protected void Page_Load(object sender, System.EventArgs e)
    {
        ds = Data();
        if (!this.IsPostBack)
        {
            if (Session["parent"] == null)
            {
                GridView1.DataSource = ds.Tables["Parent"];
                GridView1.DataBind();
            }
            else
            {
                GridView1.DataSource = Session["Parent"] as DataTable;
                GridView1.DataBind();

            }
        }
    }

    private DataSet Data()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));

        dt.Rows.Add(new object[] { 1, "aaaa" });
        dt.Rows.Add(new object[] { 2, "bbbb" });
        dt.Rows.Add(new object[] { 3, "cccc" });
        dt.TableName = "Parent";




        DataTable dtc = new DataTable();
        dtc.Columns.Add("Id", typeof(int));
        dtc.Columns.Add("Qul", typeof(string));

        dtc.Rows.Add(new object[] { 1, "aaaa" });
        dtc.Rows.Add(new object[] { 2, "bbbb" });
        dtc.Rows.Add(new object[] { 3, "bbbb" });
        dtc.TableName = "Child";


        DataSet ds = new DataSet();

        ds.Tables.Add(dt);
        ds.Tables.Add(dtc);
        Session["Parent"] = dt;

        return ds;

    }
    protected void GridView1_SelectedIndexChanged(object sender, System.EventArgs e)
    {

        DataView dv = new DataView(ds.Tables["Child"]);

        dv.RowFilter = "Id=" + this.GridView1.SelectedValue.ToString();
        DetailsView1.DataSource = dv;
        DetailsView1.DataBind();
    }

}

How To Add a User Define Section in Configuration File

ou can create your own configuration section and use one of the staic methods in the System.Configuration namespace to retrieve the information. Attached is a simple example. Also lookup configSection element and IConfigurationSectionHandler interface for additional information.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserSection.aspx.cs"
Inherits="UserSection" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <asp:GridView  ID="GridView1" runat="server">
         <Columns>
        <asp:BoundField DataField="Key" HeaderText="Key" />
        <asp:BoundField DataField="Value" HeaderText="Value" />
     
         </Columns>
          </asp:GridView>
      </div>
  </form>
</body>
</html>
Code Behind
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UserSection : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       GridView1.DataSource = ConfigExample();

       GridView1.DataBind();

   }

   private static ArrayList ConfigExample()
   {

       Hashtable htList = new Hashtable();
       System.Collections.Specialized.StringDictionary dictionary =
       (System.Collections.Specialized.StringDictionary)
       System.Configuration.ConfigurationSettings.GetConfig("MySection");
       IEnumerator iterator = dictionary.GetEnumerator();
       DictionaryEntry entry;
       while (iterator.MoveNext())
       {
           entry = (DictionaryEntry)iterator.Current;
           htList.Add(entry.Key);

       }
       return arList;
   }
}
/* IConfigurationSectionHandler Implementation */
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

/// <summary>
/// Summary description for MySectionHander
/// </summary>
namespace MyNamespace
{
   public class MySectionHandler :
System.Configuration.IConfigurationSectionHandler
   {
       #region IConfigurationSectionHandler Members

       public object Create(object parent, object configContext, XmlNode
section)
       {
           System.Collections.Specialized.StringDictionary mySection =
               new System.Collections.Specialized.StringDictionary();
           if (section == null || section.ChildNodes.Count == 0)
           {
               return mySection;
           }
           foreach (XmlNode node in section.ChildNodes)
           {
               mySection.Add(node.Attributes[0].Value,
node.Attributes[1].Value);
           }
           return mySection;
       }

       #endregion
   }
}
/* APP.CONFIG OR WEB.CONFIG */

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>

 <configSections>
   <section name="MySection" type="MyNamespace.MySectionHandler,
MyAssemblyName"/>
 </configSections>

 <MySection>
   <add key="key1" value="value1" />
   <add key="key2" value="value2" />
   <add key="key3" value="value3" />
 </MySection>

</configuration>

How To Add Please Wait message to a Button

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PleaseWaitButton.aspx.cs"
   Inherits="PleaseWaitButton" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <div>
               <asp:Button ID="Button1" runat="server" Text="Button" />
           </div>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class PleaseWaitButton : System.Web.UI.Page
{
   protected void Button1_Click(object sender, System.EventArgs e)
   {
       System.Threading.Thread.Sleep(5000);
       ClientScript.RegisterClientScriptBlock(this.GetType(), "reset",
 "document.getElementById('" + Button1.ClientID + "').disabled=false;", true);
   }

   protected void Page_Load(object sender, System.EventArgs e)
   {
       System.Threading.Thread.Sleep(5000);
       Button1.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(Button1, "") + ";
this.value='Please wait...';this.disabled = true;");
   }

}

change some text before it is sent to the client.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs"
Inherits="InterceptHtml" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           Hello World!
           <br />
           Hi
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class InterceptHtml : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

       Response.Filter = new ReplaceHTML(Response.Filter);


   }
   /// <summary>
   /// Second Method!!!!!!! overide the Render Method.
   /// </summary>
   /// <param name="writer"></param>
   protected override void Render(HtmlTextWriter writer)
   {


       StringWriter output = new StringWriter();
       base.Render(new HtmlTextWriter(output));
       writer.Write(output.ToString().Replace("Hi", "This is the replaced text!
Welcome to <a href=\"http://www.aspdotnetcodebook.blogspot.com\
">www.aspdotnetcodebook.blogspot.com</a>"));
   }
}
II nd Method
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// To intercept and get a reference to the HTML, we now need to create a
/// class to inherit System.IO.Stream. So, create a new class in
/// </summary>
public class ReplaceHTML : System.IO.Stream
{

    private System.IO.Stream Base;

    public ReplaceHTML(System.IO.Stream ResponseStream)
    {
        if (ResponseStream == null)
            throw new ArgumentNullException("ResponseStream");
        this.Base = ResponseStream;
    }






    public override int Read(byte[] buffer, int offset, int count)
    {
        return this.Base.Read(buffer, offset, count);
    }


    public override void SetLength(long value)
    {

    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        // Get HTML code 
        string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);

        // Replace the text with something else 
        HTML = HTML.Replace("Hello World!", "I've replaced the Hello World example!");

        // Send output 
        buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
        this.Base.Write(buffer, 0, buffer.Length);
    }

    public override bool CanRead
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanSeek
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanWrite
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override void Flush()
    {
        HttpContext.Current.Response.Flush();

    }

    public override long Length
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override long Position
    {
        get
        {
            throw new Exception("The method or operation is not implemented.");
        }
        set
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }

    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

How To Add Adding Paging Support to the Repeater or DataList with the PagedDataSource Class

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PagingInRepeater.aspx.cs"

   Inherits="PagingInRepeater" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="frmTest" method="post" runat="server">
       <table width="100%" border="0">
           <tr>
               <td>
                   <asp:Label ID="lblCurrentPage" runat="server"></asp:Label></td>
           </tr>
           <tr>
               <td>
                   <asp:Button ID="cmdPrev" runat="server"
Text=" << " OnClick="cmdPrev_Click"></asp:Button>
                   <asp:Button ID="cmdNext" runat="server"
 Text=" >> " OnClick="cmdNext_Click"></asp:Button></td>
           </tr>
       </table>
       <table border="1">
           <asp:Repeater ID="repeaterItems" runat="server">
               <ItemTemplate>
                   <tr>
                       <td>
                           <%# DataBinder.Eval(Container.DataItem, "Id") %>
                           </b></td>
                       <td>
                           <%# DataBinder.Eval(Container.DataItem, "FirstName") %>
                           </b></td>
                       <td>
                           <%# DataBinder.Eval(Container.DataItem, "LastName") %>
                           </b></td>
                       <td>
                           <%# DataBinder.Eval(Container.DataItem, "Address") %>
                           </b></td>
                   </tr>
               </ItemTemplate>
           </asp:Repeater>
       </table>
   </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class PagingInRepeater : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           BindRepeater();
       }

   }

   public void BindRepeater()
   {

     
       if (Session["s"] != null)
       {
           DataTable dt=new DataTable();
           dt=Session["dsTemp"] as DataTable;
           PagedDataSource objPds = new PagedDataSource();
           objPds.DataSource = dt.DefaultView;
           objPds.AllowPaging = true;
           objPds.PageSize = 3;
           objPds.CurrentPageIndex = CurrentPage;
           lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
               + objPds.PageCount.ToString();
           // Disable Prev or Next buttons if necessary
           cmdPrev.Enabled = !objPds.IsFirstPage;
           cmdNext.Enabled = !objPds.IsLastPage;
           repeaterItems.DataSource = objPds;
           repeaterItems.DataBind();

       }
       else
       {

           DataTable dt = new DataTable();
           dt = GetCustomMadeDataTable();
           PagedDataSource objPds = new PagedDataSource();
           objPds.DataSource = dt.DefaultView;
           objPds.DataSource = dt.DefaultView;
           objPds.AllowPaging = true;
           objPds.PageSize = 3;
           objPds.CurrentPageIndex = CurrentPage;
           lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
               + objPds.PageCount.ToString();
           // Disable Prev or Next buttons if necessary
           cmdPrev.Enabled = !objPds.IsFirstPage;
           cmdNext.Enabled = !objPds.IsLastPage;
           repeaterItems.DataSource = objPds;
           repeaterItems.DataBind();

       }

   }
   public DataTable GetCustomMadeDataTable()
   {
       //Create a new DataTable object
       System.Data.DataTable objDataTable = new System.Data.DataTable();
       //Create three columns with string as their type
       objDataTable.Columns.Add("Id", typeof(string));
       objDataTable.Columns.Add("FirstName", typeof(string));
       objDataTable.Columns.Add("LastName", typeof(string));
       objDataTable.Columns.Add("Address", typeof(string));
       objDataTable.Columns.Add("Email", typeof(string));
       DataRow dr;
       //Adding some data in the rows of this DataTable
       for (int i = 0; i <= 50; i++)
       {
           dr = objDataTable.NewRow();
           dr[0] = i.ToString();
           dr[1] = "FirstName" + i.ToString();
           dr[2] = "LastName" + i.ToString();
           dr[3] = "Address" + i.ToString();
           dr[4] = "Email" + i.ToString();
           objDataTable.Rows.Add(dr);

       }
       DataColumn[] dcPk = new DataColumn[1];
       dcPk[0] = objDataTable.Columns["Id"];
       objDataTable.PrimaryKey = dcPk;
       Session["dtTemp"] = objDataTable;
       return objDataTable;
   }
   public int CurrentPage
   {
       get
       {
           // look for current page in ViewState
           object o = this.ViewState["_CurrentPage"];
           if (o == null)
               return 0;    // default to showing the first page
           else
               return (int)o;
       }

       set
       {
           this.ViewState["_CurrentPage"] = value;
       }
   }
   public void cmdPrev_Click(object sender, System.EventArgs e)
   {
       // Set viewstate variable to the previous page
       CurrentPage -= 1;

       // Reload control
       BindRepeater();
   }

   public void cmdNext_Click(object sender, System.EventArgs e)
   {
       // Set viewstate variable to the next page
       CurrentPage += 1;

       // Reload control
       BindRepeater();
   }
}

How To Find Sunday and Monday Between Two Dates




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default13.aspx.cs"
Inherits="Default13" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grd" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Date" />
<asp:BoundField DataField="Value" HeaderText="Date" />

</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;

public partial class Default13 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime StartingDate = DateTime.Parse("03/29/2008");
DateTime EndingDate = DateTime.Parse("04/30/2008");

Hashtable ht=new Hashtable();
foreach (DateTime date in GetDateRange(StartingDate, EndingDate))
{
if (date.DayOfWeek.ToString() == "Monday"
|| date.DayOfWeek.ToString()=="Sunday")
{

ht.Add(date.ToShortDateString(),date.DayOfWeek.ToString());
}
}
grd.DataSource=ht;
grd.DataBind();
}
private static List<DateTime> GetDateRange(DateTime StartingDate, DateTime EndingDate)
{
if (StartingDate > EndingDate)
{
return null;
}
List<DateTime> rv = new List<DateTime>();
DateTime tmpDate = StartingDate;
do
{
rv.Add(tmpDate);
tmpDate = tmpDate.AddDays(1);
} while (tmpDate <= EndingDate);
return rv;
}
}



DateDiff Function in C#

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
    public enum DateInterval
    {
        Year,
        Month,
        Weekday,
        Day,
        Hour,
        Minute,
        Second
    }

    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = new DateTime(1994, 12, 12);
            DateTime dt2 = new DateTime(1994, 12, 12);
            long date = DateDiff(DateInterval.Day, dt1, dt2);
            Console.Write(date);

            Console.ReadLine();
        }



        public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
        {

            TimeSpan ts = ts = date2 - date1;

            switch (interval)
            {
                case DateInterval.Year:
                    return date2.Year - date1.Year;
                case DateInterval.Month:
                    return (date2.Month - date1.Month) + (12 * (date2.Year - date1.Year));
                case DateInterval.Weekday:
                    return Fix(ts.TotalDays) / 7;
                case DateInterval.Day:
                    return Fix(ts.TotalDays);
                case DateInterval.Hour:
                    return Fix(ts.TotalHours);
                case DateInterval.Minute:
                    return Fix(ts.TotalMinutes);
                default:
                    return Fix(ts.TotalSeconds);
            }
        }

        private static long Fix(double Number)
        {
            if (Number >= 0)
            {
                return (long)Math.Floor(Number);
            }
            return (long)Math.Ceiling(Number);
        }
    }
}

How to count the number of workdays between two dates and exclude holidays and weekends

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = new DateTime(1994, 12, 12, 12, 11, 33); // Start date Dec 12th
            DateTime dt2 = new DateTime(1994, 12, 31, 13, 56, 11); // End date Dec 31st
            List<DateTime> holidays = new List<DateTime>();
            holidays.Add(new DateTime(1994, 12, 14)); // Make Dec 14th a holiday
            Console.WriteLine(dt1.Date.ToShortDateString());
            Console.WriteLine(GetWorkingDays(dt1, dt2).ToString()); // without holidays
            Console.WriteLine(GetWorkingDays(dt1, dt2, holidays).ToString()); // with holidays
            Console.ReadLine();
        }

        //These crude methods assumes that DateTime b is later than DateTime a
        //If not they will just quit out and return 0
        public static int GetWorkingDays(DateTime a, DateTime b)
        {
            return GetWorkingDays(a, b, new List<DateTime>());
        }
        public static int GetWorkingDays(DateTime a, DateTime b, List<DateTime> holidays)
        {
            if (a > b) return 0;
            int c = 0;
            while (a.Date.ToShortDateString() != b.Date.ToShortDateString())
            {
                a = a.AddDays(1);
                if (!(a.DayOfWeek == DayOfWeek.Saturday || a.DayOfWeek == DayOfWeek.Sunday))
                {
                    bool isNotHoliday = true;
                    foreach (DateTime d in holidays)
                    {
                        if (d.ToShortDateString() == a.ToShortDateString())
                            isNotHoliday = false;
                    }
                    if (isNotHoliday)
                        c++;
                }
            }
            return c;
        }
    }
}

How To Use RadioButtonList as DropDownList Alternative




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PopUpRadioList.aspx.cs"
Inherits="PopUpRadioList" %>


<%@ Register TagPrefix="ajaxToolkit" Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<style type="text/css">
.popupControl
{
background-color:White;
position:absolute;
visibility:hidden;
}
</style>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DetailsView ID="dvProduct" runat="server" DefaultMode="Edit"
AutoGenerateRows="false"
Width="100%" HeaderText="Products">
<HeaderStyle BackColor="AliceBlue" Font-Bold="true" />
<FieldHeaderStyle BackColor="aliceBlue" Width="150px" Font-Bold="true" />
<RowStyle Height="20px" />
<Fields>
<asp:BoundField HeaderText="Column1" DataField="Column1" />
<asp:BoundField HeaderText="Column2" DataField="Column2" />
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<asp:TextBox ID="txtCategory" runat="server" Text='<%# Eval("Column2") %>' />
<asp:Panel ID="pnlCategories" runat="server" CssClass="popupControl">
<div style="border: 1px outset white; width: 275px">
<asp:UpdatePanel ID="Update1" runat="server">
<ContentTemplate>
<div>
<asp:RadioButtonList ID="rdoButton" runat="server"
DataSource='<%#GetCustomMadeDataTable()%>'
DataTextField="Column1" DataValueField="Id"
AutoPostBack="True"
SelectedValue='<%# Bind("Id") %>'
OnSelectedIndexChanged="rdoButton_SelectedIndexChanged">
</asp:RadioButtonList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<ajaxToolkit:PopupControlExtender ID="popupControl" runat="server"
TargetControlID="txtCategory"
PopupControlID="pnlCategories" CommitProperty="value" Position="Top">
</ajaxToolkit:PopupControlExtender>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</form>
</body>
</html>





using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AjaxControlToolkit;

public partial class PopUpRadioList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

if (Session["strTemp"] != null)
{

dvProduct.DataSource = Session["strTemp"] as DataTable;

dvProduct.DataBind();


}
else
{
dvProduct.DataSource = GetCustomMadeDataTable();


dvProduct.DataBind();
}
}



}

public DataTable GetCustomMadeDataTable()
{

//Create a new DataTable object

System.Data.DataTable objDataTable = new System.Data.DataTable();

//Create three columns with string as their type

objDataTable.Columns.Add("Id", typeof(string));
objDataTable.Columns.Add("Column1", typeof(string));
objDataTable.Columns.Add("Column2", typeof(string));
objDataTable.Columns.Add("Column3", typeof(string));


//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 0; i <= 5; i++)
{

dr = objDataTable.NewRow();
dr[0] = i.ToString();
dr[1] = "Column1Data" + i.ToString();
dr[2] = "Column2Data" + i.ToString();
dr[3] = "Column3Data" + i.ToString();
objDataTable.Rows.Add(dr);


}
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;


return objDataTable;
}
protected void rdoButton_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList rdoButtons = (RadioButtonList)sender;
PopupControlExtender popupControl =
(PopupControlExtender)rdoButtons.NamingContainer.FindControl("popupControl");

// Popup result is the selected category
popupControl.Commit(rdoButtons.SelectedItem.Text);

}
}

Highlight a Row in GridView without a postback using ASP.NET and JavaScript

Selecting a row in the GridView causes a postback. In order to highlight a row in the GridView, you have to set the ‘SelectedRowStyle’ property which takes effect when the postback occurs. In this article, we will see how to highlight a row without causing a postback. We will be using the RowCreated event of the GridView. A GridViewRow object is created for each row in the control before the GridView is rendered. Whenever a row in the GridView gets created, the RowCreated event is fired. Using this event, we can customize the behavior of the GridView. For e.g.: adding client script to the row or customizing the content of the row. Let us see an example where we will be adding some client script to the GridView. I assume that you have some experience of creating data sources and binding controls to it.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelect.aspx.cs"
Inherits="GridViewSelect" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
      <asp:GridView ID="GridView1" runat="server"
OnRowCreated="GridView1_RowCreated">
      </asp:GridView>

  </div>
  </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridViewSelect : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!IsPostBack)
      {
          if (Session["dtTemp"] != null)
          {
              GridView1.DataSource = Session["dtTemp"] as DataTable;

              GridView1.DataBind();
              this.DataBind();

          }
          else
          {
              GridView1.DataSource = GetCustomMadeDataTable();
              GridView1.DataSource = GetCustomMadeDataTable();
              this.DataBind();

          }
      }

  }
  protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
  {
      e.Row.Attributes.Add("onMouseOver", "this.style.background='#eeff00'");
      e.Row.Attributes.Add("onMouseOut", "this.style.background='#ffffff'");   
  }

  public DataTable GetCustomMadeDataTable()
  {

      //Create a new DataTable object

      System.Data.DataTable objDataTable = new System.Data.DataTable();

      //Create three columns with string as their type

      objDataTable.Columns.Add("Id", typeof(string));
      objDataTable.Columns.Add("FirstName", typeof(string));
      objDataTable.Columns.Add("LastName", typeof(string));
      objDataTable.Columns.Add("Address", typeof(string));
      objDataTable.Columns.Add("Email", typeof(string));
      DataRow dr;
      //Adding some data in the rows of this DataTable
      for (int i = 0; i <= 50; i++)
      {
          dr = objDataTable.NewRow();
          dr[0] = i.ToString();
          dr[1] = "FirstName" + i.ToString();
          dr[2] = "LastName" + i.ToString();
          dr[3] = "Address" + i.ToString();
          dr[4] = "Email" + i.ToString();
          objDataTable.Rows.Add(dr);





      }

      DataColumn[] dcPk = new DataColumn[1];
      dcPk[0] = objDataTable.Columns["Id"];
      objDataTable.PrimaryKey = dcPk;
      Session["dtTemp"] = objDataTable;
      return objDataTable;
  }
}
As you are already aware that the GridView is rendered as a HTML table and each row as . In the code shown above, we are using the Attributes property of the AttributeCollection to add extra properties to the element. The onMouseOver and the onMouseOut events are added that enable the row to change its color whenever the mouse is over a particular row. Run the application and see the color of the rows changing, that too without a postback!! Well that was a quick overview of the RowCreated event. You can also use the same event to find the index of the row clicked. Just use e.Row.DataItemIndex.ToString() to retrieve the selected row index information.

How To Split String and Display in GridView

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SplitFunctionUsingRegx.aspx.cs"
Inherits="SplitFunctionUsingRegx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
 Original String<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br />
 Separator<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
 <asp:Button ID="btnConvert" runat="server" Text="Split" OnClick="btnConvert_Click" />
 <asp:GridView ID="GridView1" runat="server"></asp:GridView>

  </div>
  </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

public partial class SplitFunctionUsingRegx : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnConvert_Click(object sender, EventArgs e)
    {
        string str = TextBox1.Text;
        string strSplit = TextBox2.Text;
        ArrayList arSplit = new ArrayList();
        Regex r = new Regex(strSplit);
        string[] s = r.Split(str);
        foreach (object o in s)
        {

            arSplit.Add(o);

        }

        GridView1.DataSource = arSplit;
        GridView1.DataBind();

    }
}

How To Change GridView Header Text At Runtime

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChangeHeaderAtRuntime.aspx.cs"
Inherits="ChangeHeaderAtRuntime" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
    <div>
  <asp:GridView ID="GridView1"  runat="server"
OnRowCreated="GridView1_RowCreated"></asp:GridView>
 
   </div>
 
   </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ChangeHeaderAtRuntime : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           if (Session["strTemp"] != null)
           {

               GridView1.DataSource = Session["strTemp"] as DataTable;

               GridView1.DataBind();


           }
           else
           {
               GridView1.DataSource = GetCustomMadeDataTable();


               GridView1.DataBind();
           }
       }

   }
   public DataTable GetCustomMadeDataTable()
   {

       //Create a new DataTable object

       System.Data.DataTable objDataTable = new System.Data.DataTable();

       //Create three columns with string as their type

       objDataTable.Columns.Add("Id", typeof(string));
       objDataTable.Columns.Add("Column1", typeof(string));
       objDataTable.Columns.Add("Column2", typeof(string));
       objDataTable.Columns.Add("Column3", typeof(string));


       //Adding some data in the rows of this DataTable
       DataRow dr;
       for (int i = 0; i <= 20; i++)
       {

           dr = objDataTable.NewRow();
           dr[0] = i.ToString();
           dr[1] = "Column1Data" + i.ToString();
           dr[2] = "Column2Data" + i.ToString();
           dr[3] = "Column3Data" + i.ToString();
           objDataTable.Rows.Add(dr);


       }
       DataColumn[] dcPk = new DataColumn[1];
       dcPk[0] = objDataTable.Columns["Id"];
       objDataTable.PrimaryKey = dcPk;
       Session["strTemp"] = objDataTable;


       return objDataTable;
   }
   protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
   {
       if (e.Row.RowType == DataControlRowType.Header)
       {
           Int32 idx = 0;
           foreach (TableCell cell in e.Row.Cells)
           {
               cell.Text = String.Format("{0}_{1}", cell.Text, (++idx));
               if (idx % 2 == 0)
               {
                   cell.HorizontalAlign = HorizontalAlign.Right;
               }
               else
               {
                   cell.BackColor = System.Drawing.Color.Blue;
                   cell.ForeColor = System.Drawing.Color.White;
               }
           }
       }

   }
}