Friday, September 11, 2009

Disable All the Controls in ASP.Net Web Forms using C#.net

To disable all the controls(label,textbox,dropdown etc) in a web form use the following function

Call the below function like: SetControlsDisable(Page);

public void SetControlsDisable(Control Page)
{
foreach (Control ctrl in Page.Controls)
{
if (ctrl is TextBox)
{
((TextBox)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is Button)
{
((Button)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is DropDownList)
{
((DropDownList)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}


if (ctrl is CheckBoxList)
{
((CheckBoxList)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is ImageButton)
{
((ImageButton)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}

if (ctrl is CheckBox)
{
((CheckBox)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}


if (ctrl is LinkButton)
{
((LinkButton)(ctrl)).Enabled = false;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetControlsDisable(ctrl);
}
}
}
}

Format Currency Textbox in US$ using AJAX in ASP.Net

The following code is used to format (display the currency value in US$ in textbox) the currency field using AJAX in asp.net

First include the AJAX Toolkit controls in your project and add the below code in your form (ASPX file)

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

Next drag and drop the text box, script manager and FilteredTextBoxExtender

Add the below code




Display the currency(US$) format in textbox in code behind

TextBox1.Text = String.Format("{0:C2}", (ds.Tables[0].Rows[0]["Price"]));

The price will display as “$250,200,000.00”

At the time of inserting the Price in DB, remove the $ and , using the below function and insert into table

public string removeFormat(string amount)
{
string replace;
replace = amount.Replace("$", "");
replace = replace.Replace(",", "");
return replace;
}

Decimal price = Convert.ToDecimal(removeFormat(TextBox1.Text));

Read Excel File using DataReader in ASP.Net using C#.Net


The following code is used to read the excel sheet using data reader in asp.net,
            using System.Data.Common;
      public void ReadXLSFile()
      {
        string Field1, Field2;
        Field1 = "";
        Field2 = "";
        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data  Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
        
 DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
        using (DbConnection connection = factory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
            using (DbCommand command = connection.CreateCommand())
            {
                command.CommandText = "SELECT Field1, Field2 FROM [Sheet1$]";
                connection.Open();
                using (DbDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        Field1 = dr["Field1"].ToString();
                        Field2 = dr["Field2"].ToString();
                    }
                }
            }
        }
    }

Thursday, September 10, 2009

Autoincrement Filed in Sql table with Initial Charecter

Here is the Function to increment the ID Field in Sql table with Initial Character

The below function will get the Tablename,Column name and Field Character(initial character) as a Parameter and return the Increment value with Field Character. Example to increment UserId, need to pass the table name, field name and character as "UI", then the function will return UI00001
public string Autoincrement(string TName, string CName, string FCode)
        {
            string Id = null;
            string strSql = null;
            string tmp = null;
            sqlconn = sqlConnection();
            strSql = "";
            strSql = "select max(cast(substring(" + CName + ",3,10)as integer))+1 from " + TName + "";
            SqlCommand SqlCmd = new SqlCommand(strSql, sqlconn);
            if (sqlconn.State == ConnectionState.Closed)
                sqlconn.Open();
            if (string.IsNullOrEmpty(SqlCmd.ExecuteScalar().ToString()))
            {
                Id = FCode + "00001";
                if (sqlconn.State == ConnectionState.Open)
                    sqlconn.Close();
                return Id;
            }
            strSql = "";
            strSql = SqlCmd.ExecuteScalar().ToString();
            if (strSql.Length == 1)
                tmp = FCode + "0000";
            else if (strSql.Length == 2)
                tmp = FCode + "000";
            else if (strSql.Length == 3)
                tmp = FCode + "00";
            else if (strSql.Length == 4)
                tmp = FCode + "0";
            else
                tmp = FCode;

            tmp = tmp + strSql;
            Id = tmp;
            if (sqlconn.State == ConnectionState.Open)
                sqlconn.Close();
            return Id;
        }

Call the above function as

string userid = Autoincrement("tblUser","UserId","UI");

Default Button in ASP.Net Form

One can set the default button at the form level meaning of all the buttons in the form the one that is set as default will be triggered whenever user presses Enter key.
To set the default button one has to do the following
<form id="index" runat="server" defaultbutton="btn1">
<asp:Button ID="btn1" runat="server" Text="Button"
    OnClick = "btn1_Click" />
<asp:Button ID="btn2" runat="server" Text="Button"
    OnClick = "btn2_Click" />
<asp:Button ID="btn3" runat="server" Text="Button"
    OnClick = "btn3_Click" />
<asp:TextBox ID="txt1" runat="server">asp:TextBox>
form>
Need to provide the ID of the Button to the defaultbutton property and it is set as default.
If you want to do it from code behind refer below (C#)
this.Form.DefaultButton = "btn1"; 
 To do the same things in Master Form, use the below code in code behind
this.Form.DefaultButton = btn1.UniqueID;
  

Prevent user from navigate to previous page using back button of the browser

Prevent user from navigate to previous page using back button of the browser or the back option in the context menu.
One cannot disable the browser back button functionality only thing that can be done is prevent them.
Below is the JavaScript snippets that needs to be placed in the head section of the page where you don’t want the user to revisit using the back button
 
Suppose there are two pages Page1.aspx and Page2.aspx and Page1.aspx redirects to Page2.aspx
Hence to prevent user from visiting Page1.aspx using Back Button you will need to place the script in the head section of Page1.aspx like in the (in above image).

 

Sql Server Date/Time Conversion

SQL Server provides a number of options you can use to format a date/time string. One of the first considerations is the actual date/time needed. The most common is the current date/time using getdate(). This provides the current date and time according to the server providing the date and time. If a universal date/time is needed, then getutcdate() should be used. To change the format of the date, you convert the requested date to a string and specify the format number corresponding to the format needed. Below is a list of formats and an example of the output:

DATE FORMATS
Format # Query(Current date : 09/10/2009 Sample

1

select convert(varchar, getdate(), 1) 09/10/09

2

select convert(varchar, getdate(), 2) 09.09.10

3

select convert(varchar, getdate(), 3) 10/09/09

4

select convert(varchar, getdate(), 4) 10.09.09

5

select convert(varchar, getdate(), 5) 10-09-09

6

select convert(varchar, getdate(), 6) 10 Sep 09

7

select convert(varchar, getdate(), 7) Sep 10, 09

10

select convert(varchar, getdate(), 10) 09-10-09

11

select convert(varchar, getdate(), 11) 09/09/10

101

select convert(varchar, getdate(), 101) 09/10/2009

102

select convert(varchar, getdate(), 102) 2009.09.10

103

select convert(varchar, getdate(), 103) 10/09/2009

104

select convert(varchar, getdate(), 104) 10.09.2009

105

select convert(varchar, getdate(), 105) 10-09-2009

106

select convert(varchar, getdate(), 106) 10 Sep 2009

107

select convert(varchar, getdate(), 107) Sep 10, 2009

110

select convert(varchar, getdate(), 110) 09-10-2009

111

select convert(varchar, getdate(), 111) 2009/09/10

Time Format:

Time Format
8 or 108 select convert(varchar, getdate(),8) 00:38:54
9 or 109 select convert(varchar, getdate(), 9) Sep 10 2009 12:38:54:840AM
14 or 114 select convert(varchar, getdate(), 14) 00:38:54:840

You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample Statement Output
select replace(convert(varchar, getdate(),101),’/',”) 09102009
select replace(convert(varchar, getdate(),101),’/',”) + replace(convert(varchar, getdate(),108),’:',”) 09102009004426

Maintain the scroll bar position in the same location

In the Page Directive of the Asp.Net Page, add the property ‘MaintainScrollPositionOnPostback’ and set its value as ‘true’.

Example:

<%@ Page CodeFile=”Default.aspx.cs” MaintainScrollPositionOnPostback=”true” Inherits=”_Default” %>

Now, the page will maintain the scroll bar position in the same location as it is before postback

Shrink the DataBase

Try the following code through your Query Analyser to shrink the database.

backup log with truncate_only
use database_name
dbcc SHRINKFILE (database_name_Log,2)
dbcc ShrinkDatabase (database_name, 2)

To set the maximum file upload size supported by Asp.Net

To set the maximum file upload size supported by Asp.Net, you must add the under section in the web.config file. The syntax is below

httpRuntime maxRequestLength=”Maximum size you want to upload in KB”
executionTimeout=”No. of seconds for Execution Time Out” />

Limit the number of characters in the Asp.Net TextArea

This tips will help you to limit the number of characters in the Asp.Net TextArea or Asp.Net Multiline Textbox. It uses a JavaScript function to limit the characters keyed in the TextArea.

Step 1: Add the below JavaScrpit function between the in your aspx page.

function fnLimitTextAreaChars(textareaName, NoOfChars)
{
if (textareaName.value.length > NoOfChars)
{
textareaName.value = textareaName.value.substring(0, NoOfChars);
}
}

Step 2: In the code-behind at Page_Load event, add the two lines as follows.

TextBox1.Attributes.Add(”onKeyDown”, “fnLimitTextAreaChars(this, 150)”);
TextBox1.Attributes.Add(”onKeyUp”, “fnLimitTextAreaChars(this, 150)”);

It’s done. Now when you type any letters in the TextArea, it will allow only first 150 characters. The rest will be truncated. Try yourself.