Thursday, March 25, 2010

Failed to access IIS metabase ASP.NET 1.1 2.0 3.5 Web Server Error




Please visit my new Web Site https://coderstechzone.com



After installing IIS server when you browsing Asp.net web site or an asp.net aspx page in IIS server then you may getting or encounter an error named "Failed to access IIS metabase".

Error Description:
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:
System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase.

Reason:
you may have installed IIS Server after installing the .NET framework.

Error Screen shot:

Metabase Error


Solution:

This Error Caused Because You does not Register ASP.Net with IIS. Please Follow the below Steps to Regiser ASP.Net With IIS:

Step 1: Go to Start then Run
Step 2: Write cmd and then press enter
Step 3: Go to your windows directory. Here i am considering c Drive
Step 4: Type C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i
Step 6: Change the path based on your local path.
Step 7: Wait a few moment until a message comes Successfully Register.

metabase solution

Note: If you multiple .net version like Asp.net 1.1,Asp.net 2.0 or Asp.net 3.5 then modify the above command accordingly & run.

Hope now your problem has been resolved.

Bind Enum Types to a DropdownList control in asp.net C#




Please visit my new Web Site https://coderstechzone.com



In some cases we need to bind Enum data into a DropdownList. So in this article or tutorial i will explain "How one can bind enum into a DropdownList in Asp.net". After searching a lot of time i found all codes are inline but i want to control enum from a single class. So that i can manage enums from a single file. As a developer we need enum in most cases like Status,Type etc. So that i want to encapsulate all my necessary enums of my project into a single class. Here i will show you how you can easily manage enums in your project and use multiple times in your pages where required.

We can declare enum in two ways. One is we can define value when we create an enum on other hand we do not need to decalere value. Please check the two types of different declaration from given below:



public enum TaskType
    {
        Development,
        Operation,
        Reporting,
        Monitoring
    }

    public enum Status
    {
        New=100,
        Started=200,
        PartiallyCompleted=35,
        Completed=400,
        Cancelled=500
    }
In the first type of declaration the value starts from 0 implicitly. But in the second type of decalaration of Enum we have declared the values instead of implicit declaration which is termed as explicit declatration. Now our concern is how we can bind those types of enum into our dropdownlist. To do this follow the below code sample:
DropDownList1.DataSource = Enum.GetNames(typeof(EnumClass.TaskType));
            DropDownList1.DataBind();

            DropDownList2.DataSource = Enum.GetNames(typeof(EnumClass.Status));
            DropDownList2.DataBind();

Now enum type data bindinng is completed. Now if we want to read the corresponding enum value based on dropdownlist selection then we can follow the code sample:
EnumClass.TaskType SelectedType = (EnumClass.TaskType)Enum.Parse(typeof(EnumClass.TaskType), DropDownList1.SelectedValue);
        Label1.Text = "Task Type:  SelectedText: " + SelectedType.ToString() + "  SelectedValue: " + SelectedType.GetHashCode();

        EnumClass.Status SelectedStatus = (EnumClass.Status)Enum.Parse(typeof(EnumClass.Status), DropDownList2.SelectedValue);
        Label2.Text = "Task Status:  SelectedText: " + SelectedStatus.ToString() + "  SelectedValue: " + SelectedStatus.GetHashCode();

If you can not understand what i am telling then follow the below complete example.

Create a new project. Add a new class & give the classname as "EnumClass". Now paste the below codes into the class:
using System;

public class EnumClass
{

    public enum TaskType
    {
        Development,
        Operation,
        Reporting,
        Monitoring
    }

    public enum Status
    {
        New=100,
        Started=200,
        PartiallyCompleted=35,
        Completed=400,
        Cancelled=500
    }

    public EnumClass()
 {
 }
}

Now add a webpage into your project and paste the below HTML markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Bind_Enum.aspx.cs" Inherits="Bind_Enum" %>

<!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>How to bind enum into dropdownlist</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    <br /><br />
    <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
    <br /><br />
    <asp:Button ID="Button1" runat="server" text="Get Selected Enum Value" OnClick="Button1_Click" />
    <br /><br />
    <hr />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <br />
    <asp:Label ID="Label2" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
Now under page_load event write the below code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = Enum.GetNames(typeof(EnumClass.TaskType));
            DropDownList1.DataBind();

            DropDownList2.DataSource = Enum.GetNames(typeof(EnumClass.Status));
            DropDownList2.DataBind();
        }

    }
Since when you run the page and click on the button control i want to read the both selected text and selected value so that under the button click event paste the below code:
protected void Button1_Click(object sender, EventArgs e)
    {
        EnumClass.TaskType SelectedType = (EnumClass.TaskType)Enum.Parse(typeof(EnumClass.TaskType), DropDownList1.SelectedValue);
        Label1.Text = "Task Type:  SelectedText: " + SelectedType.ToString() + "  SelectedValue: " + SelectedType.GetHashCode();

        EnumClass.Status SelectedStatus = (EnumClass.Status)Enum.Parse(typeof(EnumClass.Status), DropDownList2.SelectedValue);
        Label2.Text = "Task Status:  SelectedText: " + SelectedStatus.ToString() + "  SelectedValue: " + SelectedStatus.GetHashCode();
    }
Now run the project and you will get the below output:

Bind Enum Value

Hope now you can easily manage all enum types from a single class file and use in your pages when required.
Happy coding !!

Wednesday, March 10, 2010

How to Run Time Dynamically Build ConnectionString in Asp.Net




Please visit my new Web Site https://coderstechzone.com



Asp.net gives developers a class to build runtime dynamically connectionstring named SqlConnectionStringBuilder. Here in this article I will show you by an example. Please have a look at the below code example which will help you to understand how one can build dynamically connectionstring with less error possibilities.














Code Example:
using System;
using System.Data;
using System.Data.SqlClient;

public partial class Connectionstringbuilder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Build connectionstring
            SqlConnectionStringBuilder ConnBuilder = new SqlConnectionStringBuilder();

            ConnBuilder.DataSource = @".\SQLExpress"; // Name of the Sql Server instance
            ConnBuilder.InitialCatalog = "TestDB"; // Database Name
            ConnBuilder.UserID = "sa";
            ConnBuilder.Password = "your password";
            ConnBuilder.ConnectTimeout = 0;
            ConnBuilder.IntegratedSecurity = false;


            //How to use
            DataTable dt;
            String SQL = "SELECT Name,Description,Size,Color From Product  Order BY Name";
            using (SqlConnection Conn = new SqlConnection(ConnBuilder.ConnectionString))
            {
                using (SqlCommand comm = new SqlCommand(SQL, Conn))
                 {
                     Conn.Open();
                     using (SqlDataAdapter da = new SqlDataAdapter(comm))
                     {
                         dt = new DataTable("tbl");
                         da.Fill(dt);
                     }
                 }            
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}
Hope now you can dynamically build your connection string if needed.

Tuesday, March 9, 2010

How to Show hide toggle display a DIV using javascript




Please visit my new Web Site https://coderstechzone.com



In many cases developers need to show hide or toggle div container based on user requirement. Some of SEO specialists told that hiding a div is against SEO. But I want to tell that if your div appear with unchanged contents by user interaction then it’s ok for SEO. In many cases like you want to display a popup type window (which is basically a div) then you need to show or hide a div. Here in this javascript tutorial I will show you how one can manage show hide div based on user interaction.

There are two ways you can show hide a div:
1. By using CSS style.display property
2. By using CSS style.visibility property

1. By using CSS style.display property:
When you use style.display to control div appearance then in visible time it occupies its area but in hidden time it does not occupy the area. Look at below image.



Cross Browser Javascript Function / Method:
function Show_Hide_By_Display()
    {
        var div1 = document.getElementById("div1");
        if(div1.style.display=="" || div1.style.display=="block")
        {
            div1.style.display = "none";
            
        }
        else
        {
            div1.style.display = "block";
        }
        return false;
    }    

2. By using CSS style.visibility property:
When you use style.visibility to control div appearance then in visible time it occupies its area as well as in hidden time also.



Cross-Browser Javascript Function / Method:
function Show_Hide_By_Visibility()
    {
        var div1 = document.getElementById("div1");
        if(div1.style.visibility=="")
        {
            div1.style.visibility = "hidden";
            
        }
        else
        {
            div1.style.visibility = "";
        }
        return false;
    }    

So based on requirement use one of two javascript function to control the appearance of your div.

The complete source code is given below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Show_Hide_Div.aspx.cs" Inherits="Show_Hide_Div" %>

<!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>Show Hide Div using Javascript</title>
    <script type="text/javascript">
    function Show_Hide_By_Display()
    {
        var div1 = document.getElementById("div1");
        if(div1.style.display=="" || div1.style.display=="block")
        {
            div1.style.display = "none";
            
        }
        else
        {
            div1.style.display = "block";
        }
        return false;
    }    
    
    function Show_Hide_By_Visibility()
    {
        var div1 = document.getElementById("div1");
        if(div1.style.visibility=="")
        {
            div1.style.visibility = "hidden";
            
        }
        else
        {
            div1.style.visibility = "";
        }
        return false;
    }    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="div1" style="border:2px;border-style:solid;border-color:Red;width:200px">
    This is a DIV. We will toggle based on a Button Click
    </div>
    <asp:Button ID="cmd" runat="server" Text="Click to toggle a DIV" OnClientClick="return Show_Hide_By_Display()" />
    </div>
    </form>
</body>
</html>

Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

Runtime dynamically bind data into a crystal report using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



Reporting is the most sensitive part of any database driven application. Without reporting system never completed. Fortunately we found again crystal report with Asp.net which ease our life as well as reduce a lot of coding. Now we just by drag and drop can create a report within a minute. This is true that from other reporting services, crystal report is the powerful and most popular reporting tools in the IT industry. This is my first article focusing on programming with Crystal Reports with ASP.NET 3.5. In this article, I will focus on adding a Crystal Report to an ASP.NET 2.0 or 3.5 web site, design the report structure and displaying the report data using a CrystalReportViewer server control, that shipped with Visual studio.

I hope this article will cover:
1. An introduction to creating Crystal report in Asp.Net.
2. How to bind runtime data into a crystal report.




To implement a crystal report using asp.net or any other languages keep in mind two things:
1. Design the report.
2. How to bind runtime dynamic data.

1. Design the report:
A lot of way to design a report. Many developers uses many tricks to design a report. As well as i have my own way. Initially when user place a requirement for a report then I think how I can design the report. Definitely the data comes from database. So find out and enlist the database column names. In this regard my own way for simple to complex report is: I always create a dummy database view to design a report. Since any report consists on a set of tabular data, that's why I use a view to design the report. In this article i will show an example how I develop a crystal report to bind dynamic data in runtime. Basically the dummy view that I will create is only to design the report nothing else. After completion of design phase, from code behind I will bind a dynamic dataset which structure is identical as the view. So let's start my example. Suppose my client ABC School & College wants a report which will display all student list. Properties or report fields that I have identified from database are Roll, Name, Email address, Address & Admission date. Let I have a table where column names related to requirement properties are Roll, Name, Email, Address & AdDate. So first create the below table & insert some data:
CREATE TABLE [dbo].[Student]
(
 [Roll] [bigint] NOT NULL,
 [Name] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [Email] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [Address] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [AdDate] [datetime] NOT NULL
)



INSERT INTO Student
Values(1001,'Abul Kalam Azad','akalam@gmail.com','Donia, Dhaka','May 01, 2008')

INSERT INTO Student
Values(1002,'Md. Afsarul Alam','afsar@hotmail.com','Mirpur, Dhaka','May 05, 2008')

INSERT INTO Student
Values(1003,'Md. Jahangir Alam','jalam@yahoo.com','Shonir Akhra, Dhaka','May 07, 2008')

INSERT INTO Student
Values(1004,'Akhtarul Islam','akhtar123@live.com','Savar, Dhaka','May 09, 2008')

INSERT INTO Student
Values(1005,'A.K.M. Parvez','parvez@gmail.com','Uttara, Dhaka','May 11, 2008')

INSERT INTO Student
Values(1006,'Musfiqur Rahaman','musfiq@hotmail.com','Firmgate, Dhaka','May 14, 2008')

INSERT INTO Student
Values(1007,'Golam Rabbani','rabbani@yahoo.com','Dhanmondi, Dhaka','May 15, 2008')

INSERT INTO Student
Values(1008,'PC sarkar','msarkar@gmail.com','Nilkhet, Dhaka','June 01, 2008')

INSERT INTO Student
Values(1009,'ZH Khan','zkhan@tribute.com','Niketon, Dhaka','June 05, 2008')

INSERT INTO Student
Values(1010,'Bimolandu Bikash','bikash@gmail.com','Banani, Dhaka','June 09, 2008')

Run this script will create a table & insert some data which we will display in crystal report. As i told that i need to create a view which will be the exact data structure of reporting requirements. In this case my view will be:
CREATE VIEW vw_ListStudent AS
SELECT 0 Roll,'' Name,'' Email,'' Address,GETDATE() AdDate

Look at the dummy view where i didn't mention any table name just a simple SQL. Keep in mind that the column name must match with your relevant table or tables column name otherwise in runtime crystal report cannot bind data since the report structure based on the view. One another thing note that view's column datatype must be identical with your relevant table columns datatype. Such as for Admission date property i used getdate() as AdDate where getdate() return a datetime value whose column name is AdDate.

Ok now a table with data and also a view is now exist in our database. Our primary task is completed.

Now create a project. Right click on the project and select "Add new item". Select Crystal report from dialog box. The dialog box looks like:



After that select the report as a blank report from the popup like:



Now we need to connect the database where we have added the table student & the dummy view. Now the crystal report is open in your IDE. You found a "Database fields" menu under "Field explorer" window. Right click on "Database fields" menu & then select Database Expert like below:



Now from "Database Expert" window expand "Create new connection" node and double click on "OLEDB" node. A database provider window will open. Now from the provider list select "Microsoft OLEDB Provider for SQL Server" and click Next button. For better understanding look at the below image:



Now from next window you have to provide the server name, username & password. After that select the database name, where you created the student table & the dummy view. The window looks like:



Now click on Finish button. You will go back to the "Database expert" again automatically. Now again expand "OLEDB" node then you found that one node also created which is exactly same as your database name that you have provided earlier. Now expand this node and then expand dbo then expand views and from list choose the dummy view that you have created earlier in this example and move it into the right pane by clicking on ">" command. In my case the scenario looks like:




Now click OK.
Now adding the view into the report object. Look at the Database fields under field explorer you found that your selected view with column list already added. Look:



Now click on the roll column & drag it onto the report details section. Look at the below image:



Same as above, drag other columns into the report details section. Now add a textbox from toolbox into the header section of your report. You can also write something like copyright@.. into the report footer section. Look at the below image how i design the report:



Ok now our report design is completed & we will move forward to bind runtime data into the report.


2. How to bind runtime dynamic data:
In this section i will explain how you can bind data dynamically or runtime into the crystal report. To do that add a crystal report viewer server control into your default aspx page. You will found that control in the VS toolbox like:



Now go to the code behind. Under page load event write the below code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT Roll,Name,Email,Address,AdDate FROM Student";


            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }
            
            
            ReportDocument _rdStudents = new ReportDocument();
            string reportPath = Server.MapPath("Students_CrystalReport.rpt");
            _rdStudents.Load(reportPath);

            _rdStudents.SetDataSource(dt);

            CrystalReportViewer1.ReportSource = _rdStudents;

        }
    }

I think the code is self explanatory no need to describe it. One thing keep in mind that do not forget to add the below namespaces into the default.aspx.cs file:
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

Now run the project hope you will get the below output report:



That's it. Hope now you can develop or create crystal reports using asp.net C# or even in VB.Net.

Monday, March 8, 2010

Display Original Image Size in new or popup window when clicking on the thumbnail Image using javascript




Please visit my new Web Site https://coderstechzone.com



In many cases like photo album application or e-commerce website product display page or e-commerce shopping cart we need to display thumbnail image first and then when user click on this image we want to show the full or original image in a popup window. In this article i will explain how one can display a full or enlarge or zoom image from thumbnail image. The output likes below:



To do that here i am using a javascript method which is given below:
function DisplayFullImage(ctrlimg) 
    { 
        txtCode = "<HTML><HEAD>" 
        +  "</HEAD><BODY TOPMARGIN=0 LEFTMARGIN=0 MARGINHEIGHT=0 MARGINWIDTH=0><CENTER>"   
        + "<IMG src='" + ctrlimg.src + "' BORDER=0 NAME=FullImage " 
        + "onload='window.resizeTo(document.FullImage.width,document.FullImage.height)'>"  
        + "</CENTER>"   
        + "</BODY></HTML>"; 
        mywindow= window.open  ('','image',  'toolbar=0,location=0,menuBar=0,scrollbars=0,resizable=0,width=1,height=1'); 
        mywindow.document.open(); 
        mywindow.document.write(txtCode); 
        mywindow.document.close();
    }

From your aspx page you can use the above javascript method in the following way:
<asp:Image ID="Image1" BorderColor="lightgray" BorderWidth="3px" width="200px" height ="200px"  runat="server" ImageUrl = "Images/blue_flower.jpg" onclick="DisplayFullImage(this);"/>

The complete source code to do the example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Thumbnail_image.aspx.cs" Inherits="Thumbnail_image" %>

<!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>Thumbnail to original image size</title>
<script type="text/javascript">
    function DisplayFullImage(ctrlimg) 
    { 
        txtCode = "<HTML><HEAD>" 
        +  "</HEAD><BODY TOPMARGIN=0 LEFTMARGIN=0 MARGINHEIGHT=0 MARGINWIDTH=0><CENTER>"   
        + "<IMG src='" + ctrlimg.src + "' BORDER=0 NAME=FullImage " 
        + "onload='window.resizeTo(document.FullImage.width,document.FullImage.height)'>"  
        + "</CENTER>"   
        + "</BODY></HTML>"; 
        mywindow= window.open  ('','image',  'toolbar=0,location=0,menuBar=0,scrollbars=0,resizable=0,width=1,height=1'); 
        mywindow.document.open(); 
        mywindow.document.write(txtCode); 
        mywindow.document.close();
    }
</script>    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" BorderColor="lightgray" BorderWidth="3px" width="200px" height ="200px"  runat="server" ImageUrl = "Images/blue_flower.jpg" onclick="DisplayFullImage(this);"/>    
    </div>
    </form>
</body>
</html>

Hope now you can enlarge zoom original image from a thumbnail image. Run the above page by modifying image url. The page will display a thumbnail image of size 200*200. Now click on the thumbnail image will popup a window to display the full original size image.

Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

Sunday, March 7, 2010

How To Get Number of Days or Date Difference between two Dates in C# Asp.Net




Please visit my new Web Site https://coderstechzone.com



In case of date time calculation from front end we need to find out the days difference between two given dates by user. Dates may come from dtpicker or from calendar control whatever we will use asp.net built in subtract method to identified the number of days or date difference between two dates. In this article i will show you to identify datediff between two dates in both C# and Vb.Net front end Language.












C# Code:
protected void Page_Load(object sender, EventArgs e)
    {
        DateTime dTFrom;
        DateTime dTo;
        string sFrom = "April 30, 2010";
        string sTo = "May 08, 2010";
        if (DateTime.TryParse(sFrom, out dTFrom) && DateTime.TryParse(sTo, out dTo))
        {
            TimeSpan TS = dTo.Subtract(dTFrom);
            int days_Diff = TS.Days;
            Response.Write("Day diference between two dates: "+days_Diff.ToString());
        } 
    }
VB.Net Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim dTFrom As DateTime
        Dim dTo As DateTime
        Dim sFrom As String = "April 30, 2010"
        Dim sTo As String = "May 08, 2010"
        If DateTime.TryParse(sFrom, dTFrom) AndAlso DateTime.TryParse(sTo, dTo) Then
            Dim TS As TimeSpan = dTo.Subtract(dTFrom)
            Dim days_Diff As Integer = TS.Days
            Response.Write(days_Diff.ToString())
        End If
    End Sub

Hope now you can generate the date difference between two dates from a given date range.

How to detect tab key is pressed by user in javascript




Please visit my new Web Site https://coderstechzone.com



In many times we need to check or detect Tab key from cross browser javascript method to implement some business logic. In this regard here i want to show you how one can detect that user pressed or enter Tab key. One can also detect the TAB key to cancel the action. So you can do lots of work based on checking TAB key depends on user or client requirement.

Keep in mind one thing that TAB Key only fires on onkeydown and the onkeyup event.No onkeypress event is fired.








The below cross-browser javascript method will check or detect tab key pressed and popup an alert message.
function DetectTab(e) 
    {
    var KeyCode = (e.which) ? e.which : e.keyCode
    if(KeyCode==9)
        {
            alert("You have pressed Tab Key.");
        }
    }

For complete example check or read the below HTML Markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Detect_Tab_Key.aspx.cs" Inherits="Detect_Tab_Key" %>

<!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>Check detect user entered Tab Key</title>
    <script type="text/javascript">
    function DetectTab(e) 
    {
    var KeyCode = (e.which) ? e.which : e.keyCode
    if(KeyCode==9)
        {
            alert("You have pressed Tab Key.");
        }
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txt" onkeydown="DetectTab(event)"></asp:TextBox>
    </div>
    </form>
</body>
</html>

Please also note that 9 is the key code of TAB key.

Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

Thursday, March 4, 2010

Run-time Error: Control 'controlname' of type 'Button' 'TextBox' 'GridView' 'CheckBox' must be placed inside a form tag with runat=server




Please visit my new Web Site https://coderstechzone.com



I found this error in Asp.Net when i am trying to add a control dynamically in the page. The error is Control 'controlname' of type 'Button' must be placed inside a form tag with runat=server. The error comes when you trying to add the control like GridView, Button, TextBox, RadioButton, RadioButtonList, CheckBox, CheckBoxList out side the form tag of your aspx page in runtime or dynamically. There were another reason you may add those controls in your page under form tag but when you open it in other editor like dreamweaver and drag thos controls then might be a chance that the control positioned outside the form tag. This type of problems solution is just place those controls inside the form tag. The error is:

error inside form

And the solution is:

inside form solution

This was the very basic solution. In my case when i runtime or dynamically add a button then i found this error for below code:
protected void Page_Load(object sender, EventArgs e)
    {
        Button cmd = new Button();
        cmd.Text = "Click Me";
        // Error comes from this line
        this.Controls.Add(cmd);
        cmd.Click += new EventHandler(Dynamic_Method);
    }

And the solution is simple look:
protected void Page_Load(object sender, EventArgs e)
    {
        Button cmd = new Button();
        cmd.Text = "Click Me";
        this.form1.Controls.Add(cmd);
        cmd.Click += new EventHandler(Dynamic_Method);
    }

Ok thats it. If you found this error for another reason like user control rendering problem please write those as a comment.

Tuesday, March 2, 2010

Set a database to read only mode using SQL Server 2005 / 2008




Please visit my new Web Site https://coderstechzone.com



In most DBA or Database Administration purpose we need to set a Database to readonly mode. Here i will show you how you can set Database in Read Only mode for Sql server 2005 & Sql Server 2008. One thing keep in mind that you can not use same sql command for both sql server 2005 and 2008. Thats why here i will show the different ways to manage a Database to Read Only mode.

The another important note is you can not make a database read only until you set the Database in single user mode. So first set the database in single user mode. Click here to read how to set Database as single user mode.







Sql Server 2005:
Now run the below command:
EXEC sp_dboption "YourDatabaseName", "read only", "True";
After executing the above command then refresh the database. You will see that the DataBase now set to Read Only mode like below:



Now if anyone try to enter or update a data into the database he will receive the below error:
Error Message: Failed to update database "DataBaseName" because the Databse is read-only.



Now to remove the read-only mode run the below sql:
EXEC sp_dboption "YourDatabaseName", "read only", "False";

Sql Server 2008:
To make the Database read only in 2008 run the below SQL:
USE master;

GO

ALTER DATABASE databasename
SET READ_ONLY;

GO

Hope now you can perform DBA role.

WaterMark in ASP.Net TextBox Multiline TextBox TextArea using JavaScript




Please visit my new Web Site https://coderstechzone.com



Basically developers use watermark textbox to give a small hint to the user to input valid or meaningfull data. We found a lot of way to watermark a TextBox using Javascript but in this article or tutorial i will explain a very simple and easy way to implement watermark in textbox / textarea / multiline TextBox. A sample output is given below:

Watermark TextBox

The main javascript method to implement watermark is:
function WaterMarkFocus(txt, text) 
        {
            if (txt.value == text) 
            {
                txt.value = "";
                txt.style.color = "black";
            }
        }

        function WaterMarkBlur(txt, text) 
        {
            if (txt.value == "") 
            {
                txt.value = text;
                txt.style.color = "gray";
            }
        }
To implement the above sample output add an aspx page into your project then enter the below HTML markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Watermark_TextBox.aspx.cs" Inherits="Watermark_TextBox" %>

<!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>How to Implement Watermark TextBox</title>

<script language="javascript" type="text/javascript">
        function WaterMarkFocus(txt, text) 
        {
            if (txt.value == text) 
            {
                txt.value = "";
                txt.style.color = "black";
            }
        }

        function WaterMarkBlur(txt, text) 
        {
            if (txt.value == "") 
            {
                txt.value = text;
                txt.style.color = "gray";
            }
        }
    </script>    

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:textbox ID="txtSearch" Text="Use ; as a separator" onfocus="WaterMarkFocus(this,'Use ; as a separator')" onblur="WaterMarkBlur(this,'Use ; as a separator')"  runat="server" ForeColor="gray" ></asp:textbox>    
        <asp:Button runat="server" ID="cmdButton" Text="Search" />
    </div>
    </form>
</body>
</html>

Hope now one can implement watermark easily. You can apply the above technique for multiline TextBox TextArea as well.
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash