Archive

Archive for the ‘Asp.net’ Category

How to find password strength using regular expression


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox runat="server" ID="txtPassword" />
        <asp:RegularExpressionValidator runat="server" 
            ErrorMessage="Invalid Password" 
            ControlToValidate="txtPassword" 
            ID="regexPassword" 
            ValidationExpression="^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$" />
    </form>
</body>
</html>

Copy a asp.net web control using clone method


protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    PlaceHolder plh = new PlaceHolder();
    Literal literal = new Literal();
    literal.Text = "<a href=\"asp.net\"> link </a>";
    plh.Controls.Add(literal);            
    this.Controls.Add(plh);
    PlaceHolder plh_copied = new PlaceHolder();
    plh_copied = this.Clone(plh_copied, plh) as PlaceHolder;
    plh_copied = this.CopyControls(plh_copied, plh) as PlaceHolder;
    this.Controls.Add(plh_copied);            
}
public object Clone(object target,object source)
{
    if (source == null)
        throw new ArgumentNullException("Source");
    if(source.GetType()!=target.GetType())
        throw new ArgumentException("Type Mismatch");
    foreach (PropertyInfo p in source.GetType().GetProperties())
    {
        if (p.CanRead && p.CanWrite)
            p.SetValue(target, p.GetValue(source, p.GetIndexParameters()), p.GetIndexParameters());
    }
    return target;
}
public Control CopyControls(Control target, Control source )
{
    foreach (Control c in source.Controls)
    {
        Control cc = Activator.CreateInstance(c.GetType()) as Control;
        cc = this.Clone(cc, c) as Control;
        cc = this.CopyControls(cc, c);
        target.Controls.Add(cc);
        if (c.Controls.Count != 0)
        {
            Control d = new Control();
            d = this.CopyControls(d, c);
            target.Controls.Add(d);
        }
    }
    return target;
}
Categories: Asp.net, C# Tags: ,

How to find all the html tags (in this case java scripts) in serverside


protected override void Render(HtmlTextWriter writer)
{            
    string tag = "script";
    List<string> scripts = new List<string>();
    int limit = 0, lb = 0, ub = 0, length = 0;
    StringBuilder sb = new StringBuilder();
    HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
    base.Render(htw);
    string html = sb.ToString();
    length = html.Length;
    string startTag = string.Format("<{0}", tag);
    string endTag = string.Format("</{0}", tag);
    string lHtml =  html.ToLower();
    do
    {
        int s=html.ToLower().IndexOf(startTag, limit);
        if (s > 0)
        {
            lb = lHtml.IndexOf(">", s) + 1;
            limit = ub = lHtml.IndexOf(endTag, lb) - 1;
            scripts.Add(html.Substring(lb, ub - lb));
        }
        else limit = s;
    }
    while (limit > 0);
    writer.Write(html);
}
Categories: Asp.net, C# Tags: ,

How to convert HTML files to aspx files automatically – Html file converter for asp.net


Please note: This tool aim to create a asp.net web application based on html files provided. 

Download – (X86)
Source Download
Download .EXE File (X86) Only 

  1. Download and install HtmlAspxFileConverter
  2. Run from the link provided in the Programmes (HtmlAspxFileConverter)
  3. Select a source direcotry where you have static html files css java scripts and other files
  4. Select a destination folder. If destination folder excists programme deletes the folder without any prompt and if the folder does not exists creates a new folder with the give path or in a case of invalid path provide you an error
  5. Enter an namespace for the asp.net web application
  6. Click on convet button.
  7. Open up visual studio and select new project
  8. Select Web tab and select Asp.net Empty Web Application
  9. Provide suiable name and click ok
  10. Change the namespace/assembly name with the name space provide to convert html in HtmlAspxFileConverter
  11. Copy all the files convertered by HtmlAspxFileConverter to the WebApplication folder. 
  12. In the solution explorer click on show all files option at the top
  13. Select non included aspx pages and just copied other folders and files and rightclick
  14. Select Include In Project option 
  15. For VB please change the source and run the programme

Source:

public partial class HtmlAspxFileConverter : Form
{
    #region Attributes

    string strNameSpace = string.Empty;
    string head = @"
        <head runat=""server"">
            {0}
        </head>
    ";
    string body = @"
        <body{0}>
            <form id=""form1"" runat=""server"">
                {1}
            </form>
        </body>
    ";   
    private string code = @"
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.UI.WebControls;

        namespace {0}
        {{
            public partial class {1} : Page
            {{
                protected void Page_Load(object sender, EventArgs e)
                {{

                }}
            }}
        }}
    ";
    private string designer = @"
        namespace {0}
        {{
            public partial class {1}
            {{
            }}
        }}
    ";
    private string header = @"<%@ Page Language=\""C#\"" AutoEventWireup=\""true\"" 
                            CodeBehind=\""{0}.cs\"" Inherits=\""{1}.{2}\"" %>";
    string[] keywords = { "abstract""event""new""struct""as""explicit""null switch""base", 
                            "extern""object""this""bool""false""operator""throw""break", 
                            "finally""out""true""byte""fixed""""override""try", 
                            "case""float""params""typeof""catch""for""private""uint",
                            "char""foreach""protected""ulong""checkek","goto""public", 
                            "unchecked""class""if""readonly""unsafe""const""implicit", 
                            "ref""ushort""continue""in""return""using""decimal""int", 
                            "sbyte""virtual""default""interface""sealed""volatile""delegate",
                            "internal""short""void""do""is""sizeof""while""double""lock",
                            "stackalloc""else""long""static""enum""namespace""string" };

    #endregion

    #region Constructors

    public HtmlAspxFileConverter()
    {
        InitializeComponent();
    }

    #endregion

    #region Support Methods

    private void ConverHtmlFileToAspxFiles(DirectoryInfo o, DirectoryInfo n)
    {
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;
        foreach (FileInfo f in o.GetFiles())
        {
            string nfn = f.FullName.Replace(o.FullName, n.FullName);
            nfn = nfn.Replace(f.Name, textInfo.ToTitleCase(f.Name));
            if (f.Extension.ToLower().Equals(".html") || f.Extension.ToLower().Equals(".htm"))
                this.SaveAsAspx(f, new FileInfo(nfn));
            else
                File.Copy(f.FullName, nfn);
        }
        foreach (DirectoryInfo c in o.GetDirectories())
        {
            string ndn = c.FullName.Replace(o.FullName, n.FullName);
            ndn = ndn.Replace(c.Name, textInfo.ToTitleCase(c.Name));
            Directory.CreateDirectory(ndn);
            this.ConverHtmlFileToAspxFiles(c, new DirectoryInfo(ndn));
        }
    }
    private void SaveAsAspx(FileInfo h, FileInfo a)
    {
        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
        TextInfo textInfo = cultureInfo.TextInfo;
        string fn =  a.FullName;
        string fileName=string.Empty;
        if(fn.Contains("html"))fileName = fn.Replace("html""aspx");
        else if (fn.Contains("Html")) fileName = fn.Replace("Html""aspx");
        else if (fn.Contains("htm")) fileName = fn.Replace("htm""aspx");
        else if (fn.Contains("Htm")) fileName = fn.Replace("Htm""aspx");  
        string classFileName = new FileInfo(fileName).Name;
        string currentFolder = fileName.Replace(classFileName,string.Empty);
        string className = string.Empty;
        if (a.Name.Contains(h.Extension)) className = a.Name.Replace(h.Extension, string.Empty);
        else
        {
            string ext = textInfo.ToTitleCase(h.Extension);
            className = a.Name.Replace(ext, string.Empty);
        }
        if (keywords.ToList<string>().Exists(x => x.Equals(className.ToLower()))) 
            className = string.Format("_{0}", className);
        File.WriteAllText(Path.Combine(currentFolder, string.Format("{0}.cs", 
            classFileName)), string.Format(code, this.strNameSpace, className));
        File.WriteAllText(Path.Combine(currentFolder, string.Format("{0}.designer.cs", 
            classFileName)), string.Format(designer, this.strNameSpace, className));
        string html = File.ReadAllText(h.FullName);
        using (StreamWriter stream = new StreamWriter(fileName))
        {                
            stream.WriteLine(string.Format(header, classFileName, this.strNameSpace, className));
            stream.WriteLine("<html>");
            int s = html.ToLower().IndexOf(">", html.ToLower().IndexOf("<head")) + 1;
            int e = html.ToLower().IndexOf("</head") - 1;
            string headContent = e - s > 0 ? html.Substring(s, e - s) : string.Empty;
            stream.Write(string.Format(head, headContent));                
            s = html.ToLower().IndexOf("<body") + 5;
            e = html.IndexOf(">", s);
            string bodyAttributes = string.Empty;
            if (s != e && e > s) bodyAttributes = html.Substring(s, e - s);
            if (bodyAttributes.Contains(">") || bodyAttributes.Contains(">")) 
                bodyAttributes = string.Empty;                
            s = html.ToLower().IndexOf(">", html.ToLower().IndexOf("<body")) + 1;
            e = html.ToLower().IndexOf("</body") - 1;
            string bodyContent = e - s > 0 ? html.Substring(s, e - s) : string.Empty;
            string[] exts = { "html","Html","htm","Htm"};
            foreach (string ext in exts) bodyContent = bodyContent.Replace(ext, "aspx");
            stream.Write(string.Format(body, bodyAttributes, bodyContent));
            stream.WriteLine("</html>");
            stream.Close();
        }
            
    }
    private void btnConvert_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(this.txtNameSpace.Text)) throw new Exception();
            this.strNameSpace = this.txtNameSpace.Text;
            DirectoryInfo s = new DirectoryInfo(this.txtSource.Text);
            if (!s.Exists) { MessageBox.Show("Destination folder doesnot exists"); return; }
            DirectoryInfo d = new DirectoryInfo(this.txtDestiation.Text);
            if (d.Exists) this.DeleteFolder(d);
            Directory.CreateDirectory(d.FullName);
            this.toolStripStatusLabel1.Text = "Converting, please wait...";
            this.SetControlStatus(false);
            this.ConverHtmlFileToAspxFiles(s, d);
            this.SetControlStatus(true);
            this.toolStripStatusLabel1.Text = "Conversion Finished.";
        }
        catch
        {
            MessageBox.Show("There is a problem");
        }

    }
    private void SetControlStatus(bool status)
    {
        this.txtSource.Enabled = 
        this.txtDestiation.Enabled = 
        this.txtNameSpace.Enabled = 
        this.btnConvert.Enabled = 
        this.btnSelectDestination.Enabled = 
        this.btnSelectSource.Enabled = status;
    }
    public void DeleteFolder(DirectoryInfo d)
    {
        foreach (FileInfo f in d.GetFiles())
            File.Delete(f.FullName);
        foreach (DirectoryInfo c in d.GetDirectories())
            this.DeleteFolder(c);
        Directory.Delete(d.FullName);
    }

    #endregion
}
Categories: Asp.net, C# Tags: ,

How to handle errors and other messages in asp.net pages


Demo
Idea is to have a single method in the PageBase called ShowMessage(…) and whenever we need to need to display message we can have pages inherit from PageBase and add PlaceHoder to the page and call this.ShowMessage(…)

BasePage And Message Type Enumaration:

public enum MessageType { Error, Information, Success }
 
public class PageBase : Page
{
    public void ShowMessage(PlaceHolder phMessage, string message, MessageType type)
    {
        if (phMessage != null)
        {
            Panel panel = new Panel() { CssClass = string.Format("{0}Message", 
                type.ToString()) };
            Label lblMessage = new Label() { Text = message, CssClass = "MessageText" };
            panel.Controls.Add(lblMessage);
            phMessage.Controls.Add(panel);
        }
    }
}

Page – Code:

public partial class TestPageBase
{
    protected void Process(object sender, EventArgs e)
    {
        try
        {
            this.btnSave.Enabled = true;
            ///
            /// just fake exception to demonstrate
            ///
            if (DateTime.Now.Second % 3 == 0) throw new Exception();
            this.ShowMessage(this.phMessage, "Processed... You need to save data to proceed...",
                MessageType.Information);
        }
        catch
        {
            this.ShowMessage(this.phMessage, "There is problem with processing data", 
                MessageType.Error);
            this.btnSave.Enabled = false;
        }
    }
    protected void Save(object sender, EventArgs e)
    {
        try
        {
            ///
            /// save data
            ///
            this.ShowMessage(this.phMessage, "Data saved successfully...", 
                MessageType.Success);
        }
        catch
        {
            this.ShowMessage(this.phMessage, "There is a problem of saving data", 
                MessageType.Success);
        }
    }
}

Page – Markup:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <style type="text/css">
  div.ErrorMessage,
  div.InformationMessage,
  div.SuccessMessage { padding:5px; }
  div.ErrorMessage { border:solid 1px #f00background-color:#fb9d9dcolor:#000 !important; }
  div.InformationMessage { bordersolid 1px #f59600background-color:#fac26a; }
  div.SuccessMessage { border:solid 1px #298012background-color:#82cf6e;  }    
 </style>
 <script runat="server">            
 </script>
 <script language="javascript" type="text/javascript">
 </script>
</head>
<body>    
 <form id="form1" runat="server">   
  <asp:PlaceHolder runat="server" ID="phMessage" />             
  <div>
   <asp:Button runat="server" ID="btnProcess" Text="Process" OnClick="Process" />
   <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="Save" />
  </div>
 </form>
</body>
</html>

Categories: Asp.net, C#, CSS Tags: , ,

How to find folder/direcotry size – C#


protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);            
    this.Response.Write(this.FindFolderSize(new DirectoryInfo(Server.MapPath("~"))) + " MB");
}
/// <summary>
/// Find the folder size in MB
/// </summary>
/// <param name="d">Target Direcotry</param>
/// <returns>Folder Size (MB)</returns>
public double FindFolderSize(DirectoryInfo d)
{
    double size = 0;
    foreach (FileInfo f in d.GetFiles())
        size += Convert.ToDouble(f.Length) / (1024 * 1024);
    foreach (DirectoryInfo c in d.GetDirectories())
        size += this.FindFolderSize(c);
    return size;
}
Categories: Asp.net, C# Tags: ,

How to bubble up an event from usercontrol to parent page(control) (Part 2 – Without Delegates)- Asp.net


Without Delegates
Please use OnBubbleEvent of the page and caste the source (first argument) to required control (in this case a button) and compare Id or you can use object compare

UserControl (Code and Markup)
Markup
Snippet

<%@ Control Language="C#" 
            AutoEventWireup="true" 
            CodeBehind="WebUserControl.ascx.cs" 
            Inherits="ActiveTest.WebUserControl" %>
<asp:Button runat="server" ID="btnUpdate" Text="Update" />

 
Code

namespace ActiveTest
{
    public partial class WebUserControl : UserControl
    {
        public string UpdateButton         
        { 
            get { return this.btnUpdate.ID; } 
        }    
    }
 
}

Consuming Page

<%@ Page Language="C#" %>
<%@ Register Src="~/WebUserControl.ascx" TagName="wuc" TagPrefix="active" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server"> 
        protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            Button btnUpdate = source as Button;
            if (btnUpdate != null && btnUpdate.ID == this.wucTest.UpdateButton)
            {
                ///
                /// Update/ or do any requred actions
                ///
            }
            return base.OnBubbleEvent(source, args);
        }
    </script>
    <script language="javascript" type="text/javascript">
    </script>
</head>
<body>    
    <form id="form1" runat="server">        
        <div>
            <active:wuc runat="server" ID="wucTest" />
        </div>
    </form>
</body>
</html>
Categories: Asp.net, C# Tags: ,

How to combine two asp.net Menu Controls with single site map and populate second menu based on first menu selection


To handle multiple asp.net menu controls based on single site map data source:

  1. Convert all the links of the first menu to perform a postback instead of rendering as links.
  2. Use a hidden variable and __MENUTARGET and hidden button __BTNHELPER
  3. Use javascript to postback the page using __BTNHELPER.
  4. In the code behind (usually in the master page) handle button event and read the site map in to XPathDocuemnt, create navigator and perform a XPath query for the relevent node
  5. Populate the second menu with the selected XML node
  6. Use an recursive method to populate all the child menu items
  7. In this article I have not used a application variable, but it is better to hold the Web.sitemap file (XPathNavigator) instead of reading on each menu click.
  8. I have used empty namespace, but if you use a namespace (usually sitemap file comes with a namespace) you have to change to XPath logoc accordingly.

Site.Master page:

<%@ Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
    </script>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <script runat="server">
        private string script = @"
            function __doPopulateMenu(target) {{
                document.getElementById(""{0}"").value = target;
                __doPostBack(""{1}"", """");
            }}
        ";
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.Page.ClientScript.RegisterClientScriptBlock(
                this.GetType(), this.GetType().Name,
                string.Format(this.script,
                this.__MENUTARGET.ClientID,
                this.__BTNHELPER.UniqueID), true);
        }
        public string GetUrl(object target)
        {
            return string.Format("javascript:__doPopulateMenu(\"{0}\")", target);
        }
        protected void PopulateLeftNagivation(object sender, EventArgs e)
        {
            this.mnuLeftNavigation.Items.Clear();
            XPathDocument doc = new XPathDocument(Server.MapPath("~/Web.sitemap"));
            XPathNavigator navigator = doc.CreateNavigator();
            XPathNodeIterator reader = navigator.Select(
                string.Format("/siteMap/siteMapNode[@url='']/siteMapNode[@url='{0}']/siteMapNode", 
                Path.GetFileName(this.__MENUTARGET.Value)));
            this.BuildLeftMenu(this.mnuLeftNavigation.Items, reader);
        }
        private void BuildLeftMenu(MenuItemCollection items, XPathNodeIterator reader)
        {
            while (reader.MoveNext())
            {
                MenuItem item = new MenuItem(reader.Current.GetAttribute("url"string.Empty), 
                    reader.Current.GetAttribute("title"string.Empty));
                items.Add(item);
                if (reader.Current.HasChildren)
                    this.BuildLeftMenu(item.ChildItems, 
                        reader.Current.SelectChildren("siteMapNode"string.Empty));
            }
        }        
    </script>
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form runat="server">
    <asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
    <div class="page">
        <div class="main">
            <asp:UpdatePanel runat="server" ID="upnlNavigation">
                <ContentTemplate>
                    <div class="NavigationWrapper">
                        <div class="TopNanvigation">
                            <asp:SiteMapDataSource runat="server" ID="SiteMapDataSource" 
                                ShowStartingNode="false" />
                            <asp:Menu 
                                runat="server" 
                                ID="mnuTopNavigation" 
                                Orientation="Horizontal" 
                                DataSourceID="SiteMapDataSource" 
                                StaticDisplayLevels="1" 
                                MaximumDynamicDisplayLevels="0">
                                <StaticItemTemplate>
                                    <a href='<%# this.GetUrl(Eval("NavigateUrl")) %>'><%# Eval("Text"%></a>
                                </StaticItemTemplate>
                            </asp:Menu>
                        </div>
                        <div class="LeftNavigation">
                            <asp:Menu runat="server" ID="mnuLeftNavigation" />
                        </div>
                    </div>
                    <asp:Button runat="server" ID="__BTNHELPER" OnClick="PopulateLeftNagivation"
                        UseSubmitBehavior="false" style="display:none" />
                    <asp:HiddenField runat="server" ID="__MENUTARGET" />
                </ContentTemplate>
            </asp:UpdatePanel>
            <div class="MainContent">
                <asp:ContentPlaceHolder ID="MainContent" runat="server"/>
            </div>
        </div>
        <div class="clear">
        </div>
    </div>
    <div class="footer">
        
    </div>
    </form>
</body>
</html>

Web.sitemap file (please not no name space)

<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
    <siteMapNode url="" title=""  description="">
      <siteMapNode url="Page1.aspx" title="Item 1"  description="">
        <siteMapNode url="SubPage11.aspx" title="Sub Item 11" />
        <siteMapNode url="SubPage12.aspx" title="Sub Item 12" >
          <siteMapNode url="SubPage121.aspx" title="Sub Item 121" />
          <siteMapNode url="SubPage122.aspx" title="Sub Item 122" />
          <siteMapNode url="SubPage123.aspx" title="Sub Item 123" />
        </siteMapNode>
        <siteMapNode url="SubPage13.aspx" title="Sub Item 13" />
        <siteMapNode url="SubPage14.aspx" title="Sub Item 14" />
        <siteMapNode url="SubPage15.aspx" title="Sub Item 15" />
      </siteMapNode>
      <siteMapNode url="Page2.aspx" title="Item 2"  description="">
        <siteMapNode url="SubPage21.aspx" title="Sub Item 21" />
        <siteMapNode url="SubPage22.aspx" title="Sub Item 22" />
        <siteMapNode url="SubPage23.aspx" title="Sub Item 23" />
      </siteMapNode>
      <siteMapNode url="Page3.aspx" title="Item 3"  description="">
        <siteMapNode url="SubPage31.aspx" title="Sub Item 31" />
        <siteMapNode url="SubPage32.aspx" title="Sub Item 32" />
        <siteMapNode url="SubPage33.aspx" title="Sub Item 33" />
        <siteMapNode url="SubPage34.aspx" title="Sub Item 34" />
      </siteMapNode>
      <siteMapNode url="Page4.aspx" title="Item 3"  description="">
        <siteMapNode url="SubPage41.aspx" title="Sub Item 41" />
        <siteMapNode url="SubPage42.aspx" title="Sub Item 42" />
      </siteMapNode>
      <siteMapNode url="Page5.aspx" title="Item 3"  description="">
        <siteMapNode url="SubPage51.aspx" title="Sub Item 51" />
        <siteMapNode url="SubPage52.aspx" title="Sub Item 52" />
        <siteMapNode url="SubPage53.aspx" title="Sub Item 53" />
        <siteMapNode url="SubPage54.aspx" title="Sub Item 54" />
      </siteMapNode>
    </siteMapNode>
</siteMap>
Categories: Asp.net, C#, XML Tags: , ,

How to disable a button after click once ( avoid multiple submission of form data) – Asp.net


<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        function disableButton(sender) {
            sender.disabled = "disabled";
            __doPostBack(sender.name, '');
        }
    </script>
    <script runat="server">        
        protected void Save(object sender, EventArgs e)
        {
 
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button 
                runat="server" 
                ID="btnSave" 
                Text="Save" 
                OnClick="Save" 
                OnClientClick="disableButton(this)" 
                UseSubmitBehavior="false" />
        </div>
    </form>
</body>
</html>
Categories: Asp.net, JavaScript Tags: ,

How to avoid dropdownlist item crop off (Auto sizing dropdownlist, Multiline Item Dropdownlist) – Asp.net, JQuery


Demo:
It is always trickey to style dropdownlists while having very long list items. Specially if we need to squeeze dropdownlist in to narrow spots. However there are numorous ways in the web to achive this, but most of them break the concept of ‘list control’ in Asp.net. This is a very basic solution (pahaps an idea) how to keep very ListBox hidden (with very long items)  in the html and show it when we click an icon and then once we select a item it shows only the text in Multiline, in a narrow space
Example:
Asp.net Web Control exteneded from ListBox:

public class AutoDropDownList : ListBox
    {
        private string style = @"
            <style type=""text/css"">        
                #{0}Container #{0}Text {{ display:block; float:left; }}
                #{0}Container .List {{ 
                    display:none; 
                    position:absolute; 
                    float:left; 
                    margin-left:{2}px; 
                }}
                #{0}Container #{0}StaticContent {{ width:{1}px; float:left; min-height:20px; }}
                #{0}Container .Handle {{ float:right; border:solid 1px #aaa; }}
            </style>
        ";
        private string script = @"
            function displayItem() {{
                $(""#{0}Text"").text($(""#{0} option:selected"").text());
                $(""#{0}Wrapper"").hide();
            }}
            $(document).ready(function () {{
                $(""html"").click(function (event) {{            
                    if (event.target.id == ""{0}Handle"") {{
                        $(""#{0}Wrapper"").show();
                    }}
                    else
                        $(""#{0}Wrapper"").hide();
        
                }});
            }});        
        ";
        public override ListSelectionMode SelectionMode
        {
            get
            {
                return base.SelectionMode;
            }
            set
            {
                throw new NotSupportedException();
            }
        }
        public int ContentWidth { getset; }
        public AutoDropDownList()
        {
            this.CssClass = "DropDownList";
            this.ContentWidth = 250;
            this.Rows = 10;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.Attributes.Add("onclick""javascript:displayItem(this)");
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
                this.ClientID, string.Format(this.script, this.ClientID), true);
            Literal litStyles = new Literal() { Text = string.Format(this.style,
                this.ClientID, this.ContentWidth, this.ContentWidth) };
            this.Page.Header.Controls.AddAt(0, litStyles);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(string.Format("<div class=\"Auto{0}\" id=\"{1}Container\">", 
                this.CssClass, this.ClientID));
            writer.Write(string.Format("<div id=\"{0}StaticContent\" class=\"StaticContent\">", 
                this.ClientID));
            writer.Write(string.Format("<div id=\"{0}Handle\" class=\"Handle\">Drop</div>", 
                this.ClientID));
            writer.Write(string.Format("<span id=\"{0}Text\" class=\"Text\">{1}</span>", 
                this.ClientID, this.SelectedItem != null ? this.SelectedItem.Text : string.Empty));
            writer.Write("</div>");
            writer.Write(string.Format("<div id=\"{0}Wrapper\" class=\"List\">"this.ClientID));
            base.Render(writer);
            writer.Write("</div>");
            writer.Write("</div>");
        }
    }

How to use the control.

<%@ Page Language="C#" %>
<%@ Register Assembly="ActiveApplication" Namespace="ActiveApplication" TagPrefix="asp" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsPostBack)
            {
                for (int i = 0; i < 100; i++)
                    this.lstBox.Items.Add(@"
                        Very long item in the dorp downlist which will be hidden due to css width b
                        eing set to 200 - This is item " + i);
                this.lstBox.Items[5].Selected = true;
            }            
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:AutoDropDownList runat="server" ID="lstBox"></asp:AutoDropDownList>
        <asp:Button runat="server" ID="btnSave" Text="Postback" />
    </div>
    </form>
</body>
</html>

Categories: Asp.net, JQuery Tags: ,