OnClick button working only after second time Asp.NET c#

El Dj

I'm new to web development and right now I'm working on a website. I have a problem with a Save button on an ASP.Net (front end) web form (back end is in C#). The button is supposed to save data entered in a textbox to a database.

When the Save button is clicked the first time, the page just 'reloads' and clear the textbox and nothing is saved in the SQL Server database (dbo connection). Then when I click the same 'Save' button a second time after re-entering information in the textbox, it actually saves to the database and goes back to a main menu page (as expected). And if I try to re-enter different information, the save button will be working just fine.

The problem happens when a user logs in and navigate to the page where he enters the data and saves it. It will never ever work the first time.

Unfortunately because of confidential purposes, I have to omit and rename certain file paths/directories and tables name!

Here's my Asp.NET code:

<%@ Page Language="C#" debug="True" Inherits="Default" src="Default.cs"      AutoEventWireup ="true"%>
<%@ Register TagPrefix="ob" TagName="ComboTree"  Src="/obout/Combotree/ComboTree.ascx" %>
<%@ Reference Control="/obout/Combotree/ComboTree.ascx" %>

<HTML>

<HEAD>
<!-- #INCLUDE VIRTUAL="/.../" -->

</HEAD>

<BODY >
<FORM runat="server">
  <BASEFONT face="Arial, Helvetica, Sans Serif" color=black size=2>
    <TABLE height="100%" cellSpacing=0 cellPadding=0 width="780" align=Center border=0>
      <!-- #INCLUDE VIRTUAL="/.../" -->
      <TR VALIGN="top">
      <!-- #INCLUDE VIRTUAL="/.../" -->
   `enter code here`<TD vAlign=top width="100%" HEIGHT="100%">
   <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0 HEIGHT="100%">
   <!-- #INCLUDE VIRTUAL="/.../" -->  
   <TR>
      <!-- #INCLUDE VIRTUAL="/.../" -->  
      <TD vAlign=top align=left >
      <!--- START YOUR CODE HERE!!!!! --->
      <script>
        function disableListItems(checkBoxListId, disable)
        {
            // Get the checkboxlist object.
            ctr = 0;
            while(1 == 1)
            {
                checkbox = document.getElementById(checkBoxListId + "_" + ctr);
                if(checkbox == null)
                {        
                    return;
                }
                checkbox.checked = true;
                checkbox.disabled = disable;
                ctr++;
            }

        }         

        function checkForm()
        {
            var errMsg = "";
            if(isBlank(document.getElementById("tbName").value))
            {
                errMsg += "\n-Folder Name";
            }

            if(errMsg!="")
            {
                alert("The following fields cannot be left blank." + errMsg);
                return false;
            }
            return true;

        }
      </script>
      <font Class="heading">File Library - <ASP:Label ID="lbTitle" RunAt="Server"/> Folder</font>
        <INPUT Type="Hidden" ID="hdFolderID" RunAt="Server"/>
        <INPUT Type="Hidden" ID="hdParentFolderID" RunAt="Server"/>
        <TABLE CellPadding="4" CellSpacing="0" Width="100%" >
        <TR>
            <TD ColSpan="2" Class="spreadsheet_line">&nbsp;</TD>
        </TR>
        <TR>
            <TD Class="Spreadsheet"><B>Name</B></TD>
            <TD Class="Spreadsheet" Width="100%"><ASP:TextBox ID="tbName" Columns="34" RunAt="Server"/></TD>
        </TR>
        <TR VAlign="Top" Visible="False" RunAt="Server">
            <TD Class="Spreadsheet" NOWRAP><B>Description</B></TD>
            <TD Class="Spreadsheet"><ASP:TextBox ID="tbDescription" TextMode="Multiline" Cols="25" Rows="5" RunAt="Server"/></TD>
        </TR>           
        <TR>
            <TD Class="Spreadsheet"><B>Active?</B></TD>
            <TD Class="Spreadsheet"><ASP:CheckBox ID="cbActive" RunAt="Server"/></TD>
        </TR>           
        <TR Visible="False" RunAt="Server">
            <TD Class="Spreadsheet"><B>Folder</B></TD>
            <TD Class="Spreadsheet"><ob:ComboTree id="ctFolders" runat="server"/></TD>
        </TR>
        <TR VAlign="Top" ID="trLicensees" RunAt="Server">
            <TD Class="Spreadsheet"><B>Departments</B></TD>
            <TD Class="Spreadsheet">
                <ASP:DropDownList ID="ddLicensee" DataTextField="Name" DataValueField="DepartmentId" RunAt="Server"/>
                <ASP:CheckBox ID="cbAll" Text="All" RunAt="Server"/>
                <div style="text-align: left; width: 30%; margin-left:-3px">
                    <ASP:CheckBoxList ID="cblLicensees" DataTextField="Name" DataValueField="DepartmentId" style="background-color:F3F3F3" RunAt="Server"/> <!--**-->
                </div>
            </TD>
        </TR>
        <TR>
            <TD Class="Spreadsheet" Align="Right" ColSpan="2">
                <ASP:ImageButton ID="btnSave" OnClick="btnSave_OnClick" ImageUrl="/images/buttons/btnSave.gif" RunAt="Server"/>
            </TD>
        </TR>
        </TABLE>
      <!--- END YOUR CODE HERE!!!!! --->
      </TD>
      <!-- #INCLUDE VIRTUAL="/.../" -->  
   </TR>
   <!-- #INCLUDE VIRTUAL="/.../" -->  
  </TABLE>
</TD>
<!-- #INCLUDE VIRTUAL="/.../" -->  
</TR>
<!-- #INCLUDE VIRTUAL="/.../" -->  
</TABLE>
</BASEFONT>
</FORM>
</BODY>
</HTML>

And here's the (back end) code for the Save button written in C#:

    public void btnSave_OnClick(object sender, System.Web.UI.ImageClickEventArgs E){    
    int counter = int.Parse(Request.Cookies["counter"].Value);
    counter++;
    Response.Cookies["counter"].Value = counter.ToString();

    try{
    SqlConnection Conn = GetConnection();
    string SQL;
    SqlCommand Cmd;
    SqlDataReader Dtr;

        if(hdFileID.Value=="")
        {
            Response.Write("Executing Save (adding new folder to DB");
            SQL = "EXEC sp_File_Add @Name,@Description,@UserID";
            Response.Write("Save successfully executed. Added to DB");
        }
        else
        {
            Response.Write("Executing Save (saving info of folder to DB");
            SQL = "EXEC sp_File_Update @Name,@Description,@UserID,@FileID";
            Response.Write("Save successfully executed. Saved to DB");
        }




        Cmd = new SqlCommand(SQL,Conn);

        Cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar));
        Cmd.Parameters["@Name"].Value = tbName.Text;

        Cmd.Parameters.Add(new SqlParameter("@Description", SqlDbType.Text));
        Cmd.Parameters["@Description"].Value = tbDescription.Text;

        Cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Int));
        Cmd.Parameters["@UserID"].Value = Convert.ToInt32(hdUserID_Global.Value);

        if(hdFileID.Value!="")
        {
            Cmd.Parameters.Add(new SqlParameter("@FileID", SqlDbType.Int));
            Cmd.Parameters["@FileID"].Value = Convert.ToInt32(hdFolderID.Value);
        }

        Cmd.ExecuteNonQuery();

        if(hdFileID.Value=="")
        {
            SQL = "SELECT MAX(FileID) AS FileID FROM tbl_File WHERE CreatedByUserID=@UserID";
            Cmd = new SqlCommand(SQL,Conn);

            Cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Int));
            Cmd.Parameters["@UserID"].Value = Convert.ToInt32(hdUserID_Global.Value);

            Dtr = Cmd.ExecuteReader();

            if(Dtr.Read())
            {
                hdFileID.Value = Dtr["FileID"].ToString();
            }
            Dtr.Close();
        }

        SQL = "DELETE FROM tbl_FileLicense ";
        SQL += " WHERE FileID=@FileID ";

        Cmd = new SqlCommand(SQL,Conn);

        Cmd.Parameters.Add(new SqlParameter("@FileID", SqlDbType.Int));
        Cmd.Parameters["@FileID"].Value = Convert.ToInt32(hdFileID.Value.ToString());

        Cmd.ExecuteNonQuery();

        if(ddLicense.Visible)
        {
            SQL = "EXEC sp_doc_Folder_Add @FileID,@LicenseID,@UserID";
            Response.Write("Save successfully executed. Added to DB");
            Cmd = new SqlCommand(SQL,Conn);

            Cmd.Parameters.Add(new SqlParameter("@FolderID", SqlDbType.Int));
            Cmd.Parameters["@FileID"].Value = Convert.ToInt32(hdFileID.Value.ToString());

            Cmd.Parameters.Add(new SqlParameter("@LicenseID", SqlDbType.Int));
            Cmd.Parameters["@LicenseID"].Value = Convert.ToInt32(ddLicense.SelectedItem.Value.ToString());

            Cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Int));
            Cmd.Parameters["@UserID"].Value = Convert.ToInt32(hdUserID_Global.Value);

            Cmd.ExecuteNonQuery();
        }
        else
        {
        }

        Conn.Close();
        Response.Redirect("/Library/Default2.aspx?FileID=" + Request["RootFileID"].ToString());
        Response.End();
    }

    catch (Exception e){
        Response.Write("An error occurred while saving: " + e);
        Response.End();
    }

}

I've been struggling for more than 2 days on that and I don't see why the button is not firing the first time but only as from the 2nd time. Any help will be greatly appreciated. Thank you.

El Dj

I got it to work by adding EnableViewState = False in the <FORM runat="server"> tag in the asp.NET code

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

OnClick button working only after second time Asp.NET c#

From Dev

Button OnClick event not working in ASP.NET Web Form Application

From Dev

ASP.NET confirm dialog not working the second time

From Dev

function not executing for the second time after onclick

From Dev

Onclick works only after second click

From Dev

onOnClientClick is working but onClick is not working on asp.net

From Dev

jquery button click not working second time on fieldset?

From Dev

form submit after preventDefault not working until submit button is clicked a second time

From Dev

JQuery timer not working properly in second time button click after finishing first attempt

From Dev

form submit after preventDefault not working until submit button is clicked a second time

From Dev

Oulook '16: Room Finder Button missing / not working after adding it (a second time) to the Ribbon Menu

From Dev

How can I prevent a button from clicking a second time when it already has an Onclick event in C#

From Dev

JQueryUI Submit button found in dialog box only works after second time opening the dialog

From Dev

onclick not working if I add Onclient() on asp button

From Dev

Javascript only working once (not even a second time after page refresh) in Rails app

From Dev

ASP.net Dynamic Button click event not working with second foreach loop

From Dev

Button Only Works on Second Click After Reload

From Dev

HTML - Button is cancelled only after second click

From Dev

SKReceiptRefreshRequest not working the second time it is called after a cancel

From Dev

navigator alert function working after second time

From Dev

navigator alert function working after second time

From Dev

SKReceiptRefreshRequest not working the second time it is called after a cancel

From Dev

jQuery submit working after second click only

From Dev

Send Email After Button Click in ASP.net C#

From Dev

Button OnClick does not work in ASP .NET

From Dev

OnClick events not working in ASP.NET page

From Dev

Onclick of ImageButton in asp.net is not working

From Dev

React: component only rendering new values on second onClick of button

From Dev

C# Button is firing only on the second click

Related Related

  1. 1

    OnClick button working only after second time Asp.NET c#

  2. 2

    Button OnClick event not working in ASP.NET Web Form Application

  3. 3

    ASP.NET confirm dialog not working the second time

  4. 4

    function not executing for the second time after onclick

  5. 5

    Onclick works only after second click

  6. 6

    onOnClientClick is working but onClick is not working on asp.net

  7. 7

    jquery button click not working second time on fieldset?

  8. 8

    form submit after preventDefault not working until submit button is clicked a second time

  9. 9

    JQuery timer not working properly in second time button click after finishing first attempt

  10. 10

    form submit after preventDefault not working until submit button is clicked a second time

  11. 11

    Oulook '16: Room Finder Button missing / not working after adding it (a second time) to the Ribbon Menu

  12. 12

    How can I prevent a button from clicking a second time when it already has an Onclick event in C#

  13. 13

    JQueryUI Submit button found in dialog box only works after second time opening the dialog

  14. 14

    onclick not working if I add Onclient() on asp button

  15. 15

    Javascript only working once (not even a second time after page refresh) in Rails app

  16. 16

    ASP.net Dynamic Button click event not working with second foreach loop

  17. 17

    Button Only Works on Second Click After Reload

  18. 18

    HTML - Button is cancelled only after second click

  19. 19

    SKReceiptRefreshRequest not working the second time it is called after a cancel

  20. 20

    navigator alert function working after second time

  21. 21

    navigator alert function working after second time

  22. 22

    SKReceiptRefreshRequest not working the second time it is called after a cancel

  23. 23

    jQuery submit working after second click only

  24. 24

    Send Email After Button Click in ASP.net C#

  25. 25

    Button OnClick does not work in ASP .NET

  26. 26

    OnClick events not working in ASP.NET page

  27. 27

    Onclick of ImageButton in asp.net is not working

  28. 28

    React: component only rendering new values on second onClick of button

  29. 29

    C# Button is firing only on the second click

HotTag

Archive