Decrease Font Size
Increase Font Size
   BLOG

ASP.NET - How to set DefaultButton in a page that are using master page

by bryian 24. August 2009 20:43

Watch this Script in action

ASP.NET DefaultButton with MasterPages.

How To set Default Button for ENTER key pressed event

How to set DefaultButton in a page that are using master page.

Sometimes we might have two or more ASP.NET button control on the ASP.NET page and prefer certain button to cause postback when the ENTER key is pressed. The DefaultButton attributes on the HtmlForm control allow us to set the button control that will causes postback when the ENTER key is pressed. Here is a small demonstration on how to set the default button in a page with using master page.

.aspx page

<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" Runat="Server">
 
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <br />  <br />
    <asp:Button ID="Button1" runat="server" OnClientClick="javascript:alert('btn 1');" Text="Button 1" OnClick="Button1_Click" />
    <br />
    <asp:Button ID="Button2" runat="server" OnClientClick="javascript:alert('btn 2');" Text="Button 2" OnClick="Button2_Click" />
   <br />
    <asp:Button ID="Button3" runat="server" OnClientClick="javascript:alert('btn 3');" Text="Button 3" OnClick="Button3_Click" />
    <br />
   <asp:Button ID="Button4" runat="server" OnClientClick="javascript:alert('btn 4');" Text="Button 4" OnClick="Button4_Click" />
  <br />  <br />  <br />  <br />
</asp:Content>

.cs page

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Form.DefaultButton = Button4.UniqueID;
        Page.SetFocus(TextBox1);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button1 on " + DateTime.Now.ToLongTimeString();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button2 on " + DateTime.Now.ToLongTimeString();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button3 on " + DateTime.Now.ToLongTimeString();
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        Label1.Text = "You typed in: " + TextBox1.Text + " You clicked on button4 on " + DateTime.Now.ToLongTimeString();
    }

Tags: ,

ASP.NET

Cannot initialize the data source object of OLE DB provider Microsoft.Jet.OLEDB.4.0 for linked server

by bryian 24. August 2009 17:47

CREATE THE LINKSERVER FROM Excel

OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "TestLinkServer" returned message "Cannot start your application. The workgroup information file is missing or opened exclusively by another user.".

Msg 7399, Level 16, State 1, Procedure sp_tables_ex, Line 41 The OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "TestLinkServer" reported an error. Authentication failed.

Msg 7303, Level 16, State 1, Procedure sp_tables_ex, Line 41 Cannot initialize the data source object of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server " TestLinkServer".

If you happen to come across the error mentioned above, here the solution that work for me.

Step to re-produce the problem.

--CREATE THE LINKSERVER FROM Excel
EXEC sp_addlinkedserver

   @server = N'TestLinkServer',
   @provider = N'Microsoft.Jet.OLEDB.4.0',
   @srvproduct = N'Excel',
   @datasrc = N'c:\test\book1.xls',
   @provstr = N'Excel 8.0'
GO

--List all the sheets in the Excel
EXECUTE SP_TABLES_EX 'TestLinkServer'  -- throw the error message

--Solution
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'TestLinkServer',
                        @useself=N'False',
                        @locallogin=NULL,
                        @rmtuser=NULL,
                        @rmtpassword=NULL

Tags: , , , ,

SQL

Disable an ASP.NET button during PostBack with AJAX loading background image

by bryian 13. August 2009 15:57

Disable submit button after user click | Disabling an ASP.NET Button when Clicked | Disable an ASP.NET button after clicking | Page_IsValid is undefined - JavaScript error message

Disable an ASP.NET button during PostBack with AJAX loading background image

 

There are times when our applications might take an extra few seconds to respond to a click event. Some users might get impatient and click on the button more than once. We can easily avoid this type of situation by disabling the submit button during PostBack on the page by using a client side script. In this article, I will share with everyone on how to:

  1. Disable the button during PostBack with or without the present of validation control

  2. Change the button text value during PostBack

  3. Include an AJAX loading background image during PostBack

  4. How I avoided the 'Page_IsValid is undefined' JavaScript error

Before we begin, allow me to show you the structure of my project. You are welcome to download this demo.

 Projext structure
Demo 1 – Without Validation Control

Here is the content of the Jscript.js

function disableBtn(btnID, newText) {

    var btn = document.getElementById(btnID);
        setTimeout("setImage('"+btnID+"')", 10);
        btn.disabled = true;
        btn.value = newText;
}

function setImage(btnID) {
    var btn = document.getElementById(btnID);
    btn.style.background = 'url(12501270608.gif)';
}

Here is part of the Default.aspx page content.

<table>        
             <tr>
                <td></td>
                <td>                 
                     <asp:button id="btnOne" tabIndex="0" Runat="server" Text="Submit"
                        onclick="btnOne_Click" 
                        OnClientClick="disableBtn(this.id, 'Submitting...')" 
                        UseSubmitBehavior="false" />               
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="Label3" runat="server" Text=""></asp:Label></td>
            </tr>
        </table>

<script type="text/javascript" src="JScript.js"></script> 

In this page, I have a button and a label control. Let take a closer look at the button attributes.

OnClientClick="disableBtn(this.id, 'Submitting...')" - Calls the JavaScript function by passing in the button ID and the new text value that I want it to display on click.

UseSubmitBehavior="false" - Indicates that the button control should use the ASP.NET postback mechanism instead of client browser's submit mechanism ( UseSubmitBehavior Property )

For testing, I included these lines in the default.aspx.cs

protected void btnOne_Click(object sender, EventArgs e)
    {
        Thread.Sleep(2000);
        Label3.Text = DateTime.Now.ToLongTimeString();
    }


Here how's the button will look like when someone click on it.

 on click Demo 1 Output

Demo 2 – With Validation Control

Here is the output from Default2.aspx

 Demo 2 aspx page

Ops... The button is still disabled after it failed the validation process. Let modify the JavaScript to fix this problem.

 Demo 2 aspx page 2

Here is the content of the new JavaScript with comments– Jscript2.js 08/14/2009 - I found out that, in Firefox, if we hit the button and continue to the next page, and then hit the back button (or javascript:history(-1);)... the button control is still disabled. I have updated the JavaScript(JScript2) to enable the button onunload for browser other than IE

10/12/2009 - I have updated the JavaScript(JScript2) to prevent double validation.

11/14/2009 - Fix bug mentioned by CodeProject user, prodriguez13. The JavaScript will throw an error when the control to validate is not visible. To remedy this problem, I have added DisableValidators function and trigger it on onload event. This function is responsible to disable all the validators where controltovalidate is null.
* I have received several requests on getting this script to work with Image button. I managed to put together a solution for it. Let me know if you find any bugs.
* Tested on IE 7.0/8.0, FireFox, image is not showing on Google Chrome, maybe someone can shed some light on this.

   
function ResetToDefault(btn, oldValue) {
    btn.disabled = false;
    btn.value = oldValue;
}
//browser properties
var Browser = {
    Version: function() {
        var version = 999;
        if (navigator.appVersion.indexOf("MSIE") != -1) {
            version = parseFloat(navigator.appVersion.split("MSIE")[1]); return version;
        }
    },
    Name: navigator.appName,
    isIE: function() {
        if (navigator.appVersion.indexOf("MSIE") != -1) {
            return true;
        }
        return false;
    }
};

//Handle Page_Validators is not defined error
//http://www.velocityreviews.com/forums/t88987-pagevalidators-error.html
function HasPageValidators() {
    var hasValidators = false;
    try {
        if (Page_Validators.length > 0) {
            hasValidators = true;
        }
    }
    catch (error) { }

    return hasValidators;
}


function SetImage(btn) {

    if (btn.type == "image") {
        btn.src = null;
        btn.style.width = '100px';
        btn.style.height = '20px';
        btn.style.backgroundImage = 'url(http://images.ysatech.com/ajax-loader.gif)';
    }
    else {
        //somehow backgroundImage not working with IE 7
        if (Browser.isIE() && Browser.Version() === 7) {
            btn.style.background = 'url(http://images.ysatech.com/ajax-loader.gif)';
        }
        else {
            btn.style.backgroundImage = 'url(http://images.ysatech.com/ajax-loader.gif)';
        }
    }
}

//enable the button and restore the original text value for browsers other than IE
function EnableOnUnload(btn, btnText) {
    if (!Browser.isIE()) {
        window.onunload = function() {
            ResetToDefault(btn, btnText);
        };
    }
}

//check if the validator have any control to validate
function EnableValidator(validator) {
    var controlToValidate = document.getElementById(validator.controltovalidate);

    if (controlToValidate !== null) {
        // alert(controlToValidate.id);
        ValidatorEnable(validator);
        return true;
    }
    ValidatorEnable(validator, false);

    return false;
}

function disableBtn(btnID, newText) {
    var btn = document.getElementById(btnID);
    var oldValue = btn.value;
    btn.disabled = true;
    btn.value = newText;
    
    //if validator control present
    if (HasPageValidators()) {

        Page_IsValid = null;

        //http://sandblogaspnet.blogspot.com/2009/04/calling-validator-controls-from.html
        //double check, if validator not null
        if (Page_Validators !== 'undefined' && Page_Validators !== null) {
            //Looping through the whole validation collection.
            for (var i = 0; i < Page_Validators.length; i++) {

                var validator = Page_Validators[i];

                //check if control to validate is enable 
                if (EnableValidator(validator)) {

                    if (!Page_Validators[i].isvalid) { //if not valid
                        ResetToDefault(btn, oldValue); //break;
                    }
                }
            }

            //   else { //if valid
            var isValidationOk = Page_IsValid;

            alert('isValidationOk ' + isValidationOk);

            EnableOnUnload(btn, btn.value);
            if (isValidationOk !== null) {
                if (isValidationOk) {
                    SetImage(btn);
                    __doPostBack(btnID, '');
                    // break;
                }
                else { //page not valid
                    btn.disabled = false;
                }
            }
            //  }
            
        }
    }
    else { //regular, no validation control present
        // setTimeout("SetImage('" + btn + "')", 5);
        SetImage(btn);
        btn.disabled = true; btn.value = newText;
        EnableOnUnload(btn, btn.value);
    }
}

//disable those validators where controltovalidate = null
function DisableValidators() {
    //this will get rid of the Page_Validators is undefined error
    if (typeof (Page_Validators) === 'undefined')
        return;
        
    if (Page_Validators !== 'undefined' && Page_Validators !== null) {
        for (var i = 0; i < Page_Validators.length; i++) {
            var validator2 = Page_Validators[i];
            var controlToValidate2 = document.getElementById(validator2.controltovalidate);
            if (controlToValidate2 === null) {
                ValidatorEnable(validator2, false);
            }
        }
    }
    return false;
}

window.onload = DisableValidators;

Output using the new JavaScript

 Demo 2 aspx page 2  Demo 2 aspx output 3
 Demo 2 aspx output 4

Conclusion:

The main items in this project were the JavaScript (Jscript2) and the button attributes (OnClientClick, UseSubmitBehavior)

I hope someone will find this tutorial useful. If you think I still can improve this code, please leave me a feedback and share your thought.

Tested on IE 6.0/7.0 and Firefox 3.0.2

Watch this Script in action

How to check if column exists in SQL Server table

by bryian 11. August 2009 19:35

Check if column exists on SQL 2005|

How to check if column exists in SQL Server table|

SQL Checking if a column exists

Here is a brief example on how we can check if a column exists in a table. But, do we have to check this? Imagine, you wrote a t-sql to add a column into a table and someone executes it more than once. This simple check will prevent the SQL from throwing error message like Column names in each table must be unique...

	
--Create test table
IF OBJECT_ID('MyTempTable1','U') IS NOT NULL
      DROP TABLE MyTempTable1
	  CREATE TABLE MyTempTable1 (column1 varchar(2) null, column2 varchar(2) null, column3 varchar(2) )
--check point
		SELECT * FROM MyTempTable1
--Check if column4 exists before adding
IF col_length('MyTempTable1','column4') is null
  	BEGIN
   		ALTER TABLE MyTempTable1
    	ADD column4 [float] NULL
	END
	--check point
	SELECT * FROM MyTempTable1
	
	--Check if column5 exists before adding
	IF NOT EXISTS (SELECT 'b' FROM INFORMATION_SCHEMA.COLUMNS
		WHERE TABLE_NAME = 'MyTempTable1' AND COLUMN_NAME = 'column5')
		 BEGIN
		  	ALTER TABLE MyTempTable1
		    ADD column5 [float] NULL
		 END<br />
		 
		 --check point
		 SELECT * FROM MyTempTable1

How to check if a column exists in a temp table?

IF col_length('tempdb..#MyTempTableName','column4') is null
 	BEGIN
		ALTER TABLE #MyTempTableName'
		ADD column4 [float] NULL
	END