28 June 2012

clear all cotrol values of a page

<script type="text/javascript">
    function allclear()
    {    //debugger
        var elements=document.getElementsByTagName("INPUT");
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="radio")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="checkbox")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
           if (elements[i].type=="text")
                elements[i].value="";
        var elements1=document.getElementsByTagName("SELECT");
        for(i=0;i<elements1.length;i++)
            if(elements1[i].id!="" && elements1[i].id!=null)
                elements1[i].selectedIndex=0;
     }
</script>
---------------------------------------------------------------------------------------
private void ClearControls(Control c)
    {
        if (c.GetType() == typeof(System.Web.UI.WebControls.TextBox))
            ((TextBox)c).Text = "";
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButtonList))
        {
            RadioButtonList rbtl = (RadioButtonList)c;
            for (int j = 0; j < rbtl.Items.Count; j++)
                rbtl.Items[j].Selected = false;
        }
        if (c.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
            ((DropDownList)c).SelectedIndex = 0;
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButton))
            ((RadioButton)c).Checked = false;
        foreach (Control child in c.Controls)
            ClearControls(child);
}

------------------------------------------------------------------------------------------------------------------------

  private void DisableControls(Control c)
    {
        if ((c is TextBox) || (c is LinkButton) || (c is Button) || (c is CheckBox) || (c is CheckBoxList) || (c is RadioButtonList) || (c is DropDownList) || (c is Panel) || (c is ImageButton))
        {
            ((WebControl)c).Enabled = false;
        }
        foreach (Control child in c.Controls)
            DisableControls(child);
    }

make listbox items colorful

protected void Page_PreRender(object sender, EventArgs e)
{
    bool flag=false;
    foreach (ListItem li in ListBox1.Items)
    {
        if (flag)
        {
            li.Attributes.Add("class", "optred");
            flag = false;
        }
        else
        {
            li.Attributes.Add("class", "optblue");
            flag = true;
        }
    }
}
<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;} 
</style>

make webpage title scrolling

<script type="text/javascript">
    msg = "MyWebPageTitle";
    msg = "..." + msg;pos = 0;
    function scrollMSG() {
    document.title = msg.substring(pos, msg.length) + msg.substring(0, pos);
    pos++;
    if (pos >  msg.length) pos = 0
    window.setTimeout("scrollMSG()",200);
    }
    scrollMSG();
</script>

javascript handlers

// Add handler using the getElementById method
$addHandler(Sys.UI.DomElement.getElementById("Button1"), "click", toggleCssClassMethod);
// Add handler using the shortcut to the getElementById method
$addHandler($get("Button2"), "click", removeCssClassMethod);

String formats

String strVal = "a(1), a1(2), a.3(3), a'4 (4), a.5:(5)";
Regex.Replace(strVal, @"[\w\s';.&,:]+\((\d+)\)", "$1") = 1,2,3,4,5
-----------------------------------------------------------------------
string dNum = "32.123456";
string.Format("{0:c}", double.Parse(dNum)) = $32.12
string.Format("{0:n}", double.Parse(dNum)) = 32.12
string.Format("{0:D}", DateTime.Now) = Thursday, June 28, 2012
string.Format("{0:T}", DateTime.Now) = 10:59:28 AM
DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") = 28/06/2012 10:59:28
---------------------------------------------------------------------------------
decimal dNum = decimal.Parse("32.12345");
Response.Write(dNum.ToString("0.00"));

01 June 2012

image file path to byte[] format

private byte[] imgStream(string filePath)
{
MemoryStream stream = new MemoryStream();
tryagain:
try
{ Bitmap bmp = new Bitmap(filePath);
  bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { goto tryagain; }
return stream.ToArray();
}

System.Drawing.ColorTranslator.FromHtml("#D8BFD8");

25 May 2012

Get RowCount all tables of a Database in SqlServer

SELECT [TableName] = O.name, [RowCount] =MAX(I.rows)FROM sysobjects O, sysindexes I
WHERE O.xtype ='U'AND I.id =OBJECT_ID(O.name)
GROUP BY O.name ORDER BY [RowCount] DESC

Email validation javascript

function emailCheck(str)
{
var at="@";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (str.indexOf(at)==-1)
    return false;
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
    return false;
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
    return false;
if (str.indexOf(at,(lat+1))!=-1)
    return false;
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
    return false;
if (str.indexOf(dot,(lat+2))==-1)
   return false;
if (str.indexOf(" ")!=-1)
   return false;
return true;
}

18 April 2012

Get current date n time in sqlserver

select current_timestamp
go
select {fn now()}
go
select getdate()
go
select convert(varchar,getdate(),101)*
go
sqlserver2005 -- select convert(varchar(8),getdate(),108), convert(varchar(8),getdate(),101) 
sqlserver2008 -- select convert(time,getdate()), convert(date,getdate(),101)

 *Each style will give the output of the date in a different format.
The default style it uses is 100.
The style values can be ranging between 100-114, 120, 121, 126, 127, 130 and 131 or 0 to 8, 10, 11, 12 and 14 in this case century part will not returned.

29 March 2012

get web.config appsettings in javascript

var conn = '<%=ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString %>'
alert(conn);

var v1 = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
var v1 = '<%=ConfigurationManager.AppSettings["var1"] %>'

<%$AppSettings:Title%>

alert(v1);

 

28 March 2012

restrict textbox to allow only numerics

function numerics()
{
 key = String.fromCharCode(window.event.keyCode);
 if (!(key >= '0' && key <= '9'))   window.event.keyCode=0;
}
<asp:TextBox ID="txt1" Text=""  runat="server"  onkeypress=" return numerics();"></asp:TextBox>

function isAlpha(keyCode)
{
    return ((keyCode >= 65 && keyCode <= 90) || keyCode == 8||keyCode==37||keyCode==39||keyCode==9||keyCode==46)
}

function isNum(keyCode)
{
    return((keyCode < 105 && keyCode > 96)||(keyCode < 57 && keyCode > 48) || keyCode == 8||keyCode==37||keyCode==39||keyCode==9||keyCode==46)
}

<asp:TextBox ID="txtUserName" runat="server" onkeydown = "return isAlpha(event.keyCode);" onpaste =  "return false;" Width="130px"></asp:TextBox>

public static bool IsNumeric(String strVal)
    {
        Regex reg = new Regex("[^0-9-]");
        Regex reg2 = new Regex("^-[0-9]+$|^[0-9]+$");
        return (!reg.IsMatch(strVal) && reg2.IsMatch(strVal));
    }

21 March 2012

check all checkboxes in a form

$(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });

checkbox list javascript validation

function valid()
    {   
       var chkBoxList = document.getElementById('<%=CheckBoxList11.ClientID %>');
        var chkBoxCount= chkBoxList.getElementsByTagName("input");
        var k=0;
        for(var i=0;i<chkBoxCount.length;i++)
        {
            if(chkBoxCount[i].checked)
            k++;
        }
        if(k==0)
        alert("select any item");
        return false;
    }

13 March 2012

Remove duplicates from an interger array

int[] a = { 1, 3, 2, 5, 6, 1, 2, 3 };
string s =",";
for (int i = 0; i < a.Length - 1; i++)
{
if (!s.Contains("," + a[i].ToString() + ","))
{
s += "," + a[i].ToString() + ",";
}
}
string ss = s.Replace(",,",",");
string sss = ss.Substring(1,ss.Length-2).Trim();
string[] aa = ss.Split(',');
int[] n=new int[ss.Split(',').Length-2];
for (int i=1;i<aa.Length-1;i++)
{
        if (aa[i].Replace(",", "")!="")
        n[i-1] = int.Parse(aa[i].Replace(",",""));
}
return n;