Wednesday, August 6, 2014

MultiSelect DropDownList with CheckBoxes in C#.Net


aspx Page
=============================================================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>
<style type="text/css">
    .DivClose
    {
         display:none;
         position:absolute;
         width:250px;
         height:220px;
         border-style:solid;
         border-color:Gray;
         border-width:1px;
         background-color:#99A479;
    }

    .LabelClose
    {
         vertical-align:text-top;
         position:absolute;
         bottom:0px;
         font-family:Verdana;
    }

    .DivCheckBoxList
    {
         display:none;
         background-color:White;
         width:250px;
         position:absolute;
         height:200px;
         overflow-y:auto;
         overflow-x:hidden;
         border-style:solid;
         border-color:Gray;
         border-width:1px;
    }

    .CheckBoxList
    {
         position:relative;
         width:250px;
         height:10px;
         overflow:scroll;
         font-size:small;
    }
</style>
<script type="text/javascript">
   var timoutID;

   //This function shows the checkboxlist
   function ShowMList()
   {
       var divRef = document.getElementById("divCheckBoxList");
       divRef.style.display = "block";
       var divRefC = document.getElementById("divCheckBoxListClose");
       divRefC.style.display = "block";
   }

   //This function hides the checkboxlist
   function HideMList()
   {
       document.getElementById("divCheckBoxList").style.display = "none";
       document.getElementById("divCheckBoxListClose").style.display = "none";
   }

   //This function finds the checkboxes selected in the list and using them,
   //it shows the selected items text in the textbox (comma separated)
   function FindSelectedItems(sender,textBoxID)
   {
       var cblstTable = document.getElementById(sender.id);
       var checkBoxPrefix = sender.id + "_";
       var noOfOptions = cblstTable.rows.length;
       var selectedText = "";
       for(i=0; i < noOfOptions ; i++)
       {
          if(document.getElementById(checkBoxPrefix+i).checked)
          {
             if(selectedText == "")
                selectedText = document.getElementById
                                   (checkBoxPrefix+i).parentNode.innerText;
             else
                selectedText = selectedText + "," +
                 document.getElementById(checkBoxPrefix+i).parentNode.innerText;
          }
       }
       document.getElementById(textBoxID.id).value = selectedText;
    }
</script>   
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="lbl" runat ="server" Font-Names ="Tahoma" Font-Size ="8pt" Font-Bold="true">MultiSelect DropDownList:</asp:Label>
        <div id="divCustomCheckBoxList" runat="server" onmouseover="clearTimeout(timoutID);"
            onmouseout="timoutID = setTimeout('HideMList()', 750);">
            <table>
                <tr>
                    <td align="right" class="DropDownLook">
                        <input id="txtSelectedMLValues" type="text" readonly="readonly" onclick="ShowMList()"
                            style="width: 229px;font: normal 8pt tahoma;" runat="server" />
                    </td>
                    <td align="left" class="DropDownLook">
                        <img id="imgShowHide" runat="server" src="drop.gif" onclick="ShowMList()" style="text-align: left;"
                            alt="0" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" class="DropDownLook">
                        <div>
                            <div runat="server" id="divCheckBoxListClose" class="DivClose">
                                <label runat="server" onclick="HideMList();" class="LabelClose" id="lblClose">
                                    x</label>
                            </div>
                            <div runat="server" id="divCheckBoxList" class="DivCheckBoxList">
                                <asp:CheckBoxList ID="lstMultipleValues" runat="server" Width="250px" Font-Names ="Tahoma" Font-Size ="8pt" CssClass="CheckBoxList">
                                </asp:CheckBoxList>
                            </div>
                        </div>
                    </td>
                </tr>
            </table>
        </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 Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lstMultipleValues.Items.Add("Asia");
        lstMultipleValues.Items.Add("Europe");
        lstMultipleValues.Items.Add("Australia");
        lstMultipleValues.Items.Add("North America");
        lstMultipleValues.Items.Add("South America");
        lstMultipleValues.Items.Add("Africa");
        lstMultipleValues.Items.Add("Antarctica");

        lstMultipleValues.Attributes.Add("onclick", "FindSelectedItems(this," + txtSelectedMLValues.ClientID + ");");
    }
}

List Files and Folders in C#.Net





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ListFilesAndFolders
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            folderBrowser1.ShowDialog(this);
            String str = DirSearch(folderBrowser1.SelectedPath);
            txtFiles .Text = str;
        }

        private String DirSearch(string sDir)
        {
            try
            {
                String strFile = String.Empty;
                String strNo = String .Empty ;
                Int32 nCount = 0;
                this.Cursor = Cursors.WaitCursor;
                foreach (string f in Directory.GetFiles(sDir))
                {
                    if (chkWithNumber.Checked == true) strNo = Convert.ToString(nCount + 1) + ". "; else strNo = "";

                    strFile = strFile + strNo + f + "\r\n";
                    nCount = nCount + 1;
                }

                foreach (string d in Directory.GetDirectories(sDir))
                {
                    foreach (string f in Directory.GetFiles(d))
                    {
                        if (chkWithNumber.Checked == true) strNo = Convert.ToString(nCount + 1) + ". "; else strNo = "";
                        strFile =strFile + strNo + f + "\r\n";
                        nCount = nCount + 1;
                    }
                    DirSearch(d);
                }
               
                lblCount.Text = "File Count :" + Convert.ToString ( nCount);
                this.Cursor = Cursors.Default;

                return strFile;
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
                return "";
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtFiles.Clear();
        }
    }
}

Monday, August 4, 2014

Export to Microsoft Excel from Datatable in C#.Net

public void ExportToExcel(DataTable dt)
{
 if (dt.Rows.Count > 0)
 {
  string filename = "Sample.xls";
  System.IO.StringWriter tw = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);


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


  //Get HTML for the control.
  Grid1.RenderControl(hw);


  Response.ContentType = "application/vnd.ms-excel";
  Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
  this.EnableViewState = false;
  Response.Write(tw.ToString());
  Response.End();
 }
}


public override void VerifyRenderingInServerForm(Control control)
{


}
 

Create Dynamic TreeView from DataTable in C#.Net





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;


public partial class DynamicTreeView : System.Web.UI.Page
{
    TreeNode tn;
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateDynamicTreeView();
    }

    private void CreateDynamicTreeView()
    {
        try
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("MenuID");
            dt.Columns.Add("MenuName");
            dt.Columns.Add("ParentID");


            DataRow dr = dt.NewRow();
            dr["MenuID"] = "0";
            dr["MenuName"] = "Earth";
            dr["ParentID"] = "Null";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "1";
            dr["MenuName"] = "Europe";
            dr["ParentID"] = "0";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "2";
            dr["MenuName"] = "Asia";
            dr["ParentID"] = "0";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "3";
            dr["MenuName"] = "Africa";
            dr["ParentID"] = "0";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "4";
            dr["MenuName"] = "Germany";
            dr["ParentID"] = "1";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "5";
            dr["MenuName"] = "France";
            dr["ParentID"] = "1";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "6";
            dr["MenuName"] = "China";
            dr["ParentID"] = "2";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "7";
            dr["MenuName"] = "India";
            dr["ParentID"] = "2";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "8";
            dr["MenuName"] = "UAE";
            dr["ParentID"] = "2";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "9";
            dr["MenuName"] = "Egypt";
            dr["ParentID"] = "3";
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["MenuID"] = "10";
            dr["MenuName"] = "Libya";
            dr["ParentID"] = "3";
            dt.Rows.Add(dr);


            foreach (DataRow dr1 in dt.Select("ParentID = 'Null'"))
            {
                TreeView1.Nodes.Add(new TreeNode(dr1["MenuName"].ToString(), dr1["MenuID"].ToString()));
            }

            foreach (DataRow dr2 in dt.Select("ParentID <> 'Null'"))
            {
                TreeNode tnd = new TreeNode(dr2["MenuName"].ToString(), dr2["MenuID"].ToString());
                TraverseTree(TreeView1.Nodes, dr2["ParentID"].ToString());

                tn.ChildNodes.Add(tnd);
            }
        }
        catch (Exception ex)
        {
            String strErr = ex.Message.ToString();
        }
    }

    void TraverseTree(TreeNodeCollection nodes, String strVal)
    {
        foreach (TreeNode child in nodes)
        {
            if (child.Value == strVal)
            {
                tn = child;
            }
            else
            {
                TraverseTree(child.ChildNodes, strVal);
            }
        }
    }
}

ASP.Net TreeView CheckBox select deselect all using Javascript (C#.Net)


//Code Behind:
//----------------------------------------
    protected void Page_Load()
    {
        TreeView1.Attributes.Add("onclick", "OnTreeClick(event)");
    } 
   
    protected void CreateSampleTreeView()
    {
        TreeNode tndEarth = new TreeNode("Earth", "Earth"); TreeView1.Nodes.Add(tndEarth);
        TreeNode tndEurope = new TreeNode("Europe", "Europe"); tndEarth.ChildNodes.Add(tndEurope);
        TreeNode tndAsia = new TreeNode("Asia", "Asia"); tndEarth.ChildNodes.Add(tndAsia);
        TreeNode tndAfrica = new TreeNode("Africa", "Africa"); tndEarth.ChildNodes.Add(tndAfrica);
        TreeNode tndUK = new TreeNode("United Kingdom", "United Kingdom"); tndEurope.ChildNodes.Add(tndUK);
        TreeNode tndFrance = new TreeNode("France", "France"); tndEurope.ChildNodes.Add(tndFrance);
        TreeNode tndGermany = new TreeNode("Germany", "Germany"); tndEurope.ChildNodes.Add(tndGermany);
        TreeNode tndChina = new TreeNode("China", "China"); tndAsia.ChildNodes.Add(tndChina);
        TreeNode tndUAE = new TreeNode("UAE", "UAE"); tndAsia.ChildNodes.Add(tndUAE);
        TreeNode tndIndia = new TreeNode("India", "India"); tndAsia.ChildNodes.Add(tndIndia);
        TreeNode tndEgypt = new TreeNode("Egypt", "Egypt"); tndAfrica.ChildNodes.Add(tndEgypt);
        TreeNode tndKahira = new TreeNode("Kahira", "Kahira"); tndAfrica.ChildNodes.Add(tndKahira);
    }
 
//Javascript inside aspx page:
//----------------------------------------

    <script type="text/javascript">
    function OnTreeClick(evt)
    {
        var src = window.event != window.undefined ? window.event.srcElement : evt.target
        var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
        if (isChkBoxClick)
        {
            var parentTable = GetParentByTagName("table", src);
            var nxtSibling = parentTable.nextSibling;
            if (nxtSibling && nxtSibling.nodeType == 1)//check if nxt sibling is not null & is an element node
            {
                if (nxtSibling.tagName.toLowerCase() == "div")//if node has children
                {
                    //check or uncheck children at all levelsCheckUncheckChildren(parentTable.nextSibling, src.checked);
                }
            }
        //check or uncheck parents at all levelsCheckUncheckParents(src, src.checked);
        }
    }

    function CheckUncheckChildren(childContainer, check)
    {
        var childChkBoxes = childContainer.getElementsByTagName("input");
        var childChkBoxCount = childChkBoxes.length;
        for (var i = 0; i < childChkBoxCount; i++)
        {
            childChkBoxes[i].checked = check;
        }
    }


    function CheckUncheckParents(srcChild, check)
    {
            var parentDiv = GetParentByTagName("div", srcChild);
            var parentNodeTable = parentDiv.previousSibling;
            if (parentNodeTable)
            {
                var checkUncheckSwitch;
                if (check) //checkbox checked
                {
                    checkUncheckSwitch = true;
                }


                else //checkbox unchecked
                {
                    var isAllSiblingsUnChecked = AreAllSiblingsUnChecked(srcChild);
                    if (!isAllSiblingsUnChecked)checkUncheckSwitch = true;
                    elsecheckUncheckSwitch = false;
                }
            var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
            if (inpElemsInParentTable.length > 0)
            {
                var parentNodeChkBox = inpElemsInParentTable[0];parentNodeChkBox.checked = checkUncheckSwitch;
                //do the same recursivelyCheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
            }
        }
    }

    function AreAllSiblingsUnChecked(chkBox)
    {
        var parentDiv = GetParentByTagName("div", chkBox);
        var childCount = parentDiv.childNodes.length;

        for (var i = 0; i < childCount; i++)
        {
            if (parentDiv.childNodes[i].nodeType == 1) //check if the child node is an element node
            {
                if (parentDiv.childNodes[i].tagName.toLowerCase() == "table")
                {
                    var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
                    //if any of sibling nodes are not checked, return falseif (prevChkBox.checked)
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //utility function to get the container of an element by tagname
    function GetParentByTagName(parentTagName, childElementObj)
    {
        var parent = childElementObj.parentNode;
        while (parent.tagName.toLowerCase() != parentTagName.toLowerCase())
        {
            parent = parent.parentNode;
        }
        return parent;
    }
</script>


Sunday, August 3, 2014

Create DataTable from Text File in C#.Net

   
//Sample.txt ==============================
// SrNo Item ModifiedOn FileType
// 1 Item1 01-Apr-14 pdf
// 2 Item2 12-Feb-14 doc
// 3 Item3 01-Dec-13 xls
// 4 Item4 18-Sep-13 ppt
// 5 Item5 15-Aug-13 txt
 


//Method ==============================
private DataTable fnGetDataTableFromTextFile(string strFileName)
    {
        strFileName = "D:Sample.txt";
        string strText = System.IO.File.ReadAllText(strFileName);

        string[] arrLine = strText.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        DataTable dt = new DataTable();

        int i = 0; int j = 0;
        string[] arrCol = arrLine[0].ToString().Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
        for (j = 0; j <= arrCol.GetUpperBound(0); j++)
        {
            dt.Columns.Add(new DataColumn(arrCol[j].ToString()));
        }

        for (i = 1; i <= arrLine.GetUpperBound(0); i++)
        {
            arrCol = arrLine[i].ToString().Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
            DataRow dr = dt.NewRow();

            for (j = 0; j <= arrCol.GetUpperBound(0); j++)
            {
                dr[j] = arrCol[j];
            } dt.Rows.Add(dr);
        }

        return dt;
    }

Friday, August 1, 2014

List SQL Server Table and Columns properties

List SQL Server Table and Columns properties

USE [Northwind];
SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],  
      T.[name] AS [table_name], AC.[name] AS [column_name],  
      TY.[name] AS system_data_type, AC.[max_length],
      AC.[precision], AC.[scale], AC.[is_nullable], AC.[is_ansi_padded]
FROM sys.[tables] AS T  
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] AND AC.[user_type_id] = TY.[user_type_id]  
WHERE T.[is_ms_shipped] = 0
ORDER BY T.[name], AC.[column_id]
 
and the result is below:




 
 

Monday, July 28, 2014

Show Popup Message in C#.Net

Show Popup Message in C#.Net

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ShowPopUpMsg ("This is popup message.");
    }

    private void ShowPopUpMsg(string msg)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("alert('");
        sb.Append(msg.Replace("\n", "
\\n").Replace("\r", "").Replace("'", "\\'"));
        sb.Append("');");
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
    }
}

Wednesday, July 16, 2014

Export to Excel in C#.Net

Sample Export to Excel from C#.Net

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CarlosAg.ExcelXmlWriter;

public class ExportData
{
 [STAThread]
 public void ExportToExcel()
 {
  Workbook book = new Workbook();
  Worksheet sheet = book.Worksheets.Add("Sheet1"); 
  WorksheetRow row =  sheet.Table.Rows.Add(); 
  row.Cells.Add("Hello World");
  book.Save(@"D:\Test1.xls");
 }
}

Sample Web Service and Client project


Sample Web Service Code file:

using System;
using System.Web.Services;
using System.Xml.Serialization;
[WebService(Namespace = "http://localhost/MyWebServices/")]
public class FirstService : WebService
{
    [WebMethod]
    public int Add(int a, int b)
    {
        return a + b;
    }
    [WebMethod]
    public String SayHello()
    {
        return "Hello World";
    }
}

 
Sample Web Service Client Code file:

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.IO;
using FirstService;
public partial class _Default : System.Web.UI.Page
{
    protected void runSrvice_Click(Object sender, EventArgs e)
    {
        FirstService.FirstService mySvc = new FirstService.FirstService();
        Label1.Text = mySvc.SayHello();
        Label2.Text = mySvc.Add(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text)).ToString();
    }
}