How to prevent PostBack while clicking button in ASP.NET - asp.net

The following picture is view of one of my WebForms in project. I am currently facing following problem: I am loading CSV file, the program analyzes it and displays it as a Table. Then, using DropDownLists and Textboxes below, user chooses day, project and hours in order to decrease hours, which have been assigned to the project (imagine project x, which has budget of 100.000$ and has 150h to be burned by workers. Each worker burns his own hours and web admin can see how many hours can be burned and how does the budget look like). When I decrease hours for some day, for example project x, Monday, 8h- the page reloads and all the things, including table, dropdownlists and textboxes are closed and user add project hours for another days.
Please see the code that is responsible for changes in the database and is executed during Submit button click:
private void decreaseProjHours()
{
if (IsPostBack)
{
string nameOfProject = DropDownList1.SelectedValue;
int dayID = DropDownList2.SelectedIndex;
int hours = Convert.ToInt32(TextBox3.Text);
if ((nameOfProject == "") || (dayID > 7 || dayID < 0) || hours < 0)
{
Response.Write("You have entered invalid data in one of the fields!");
return;
}
//decreasing from total hours assigned to project
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WorkTimeDBConnectionString"].ConnectionString);
conn.Open();
string getTotalProjectH = "select hours from projects where project_name='" + nameOfProject + "'";
SqlCommand com = new SqlCommand(getTotalProjectH, conn);
int check = Convert.ToInt32(com.ExecuteScalar().ToString());
if (check - hours < 0)
{
Response.Write("No more hours can be reported for project" + nameOfProject);
conn.Close();
return;
}
else
{
try
{
string tryUpdate = "update projects set hours='" + (check - hours) + "'" + " where project_name='" + nameOfProject + "'";
SqlCommand com1 = new SqlCommand(tryUpdate, conn);
com1.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
conn.Close();
return;
}
}
}
}
Is is the problem with PostBack? I already tried making OnClientClick return false and Button3.Attributes.Add("onclick", "return false;")- the operation of modifying the database fails then and nothing is submitted.
What should I do? Is it really problem with PostBack or something else refreshes my webpage?
EDIT:
Button3.Attributes.Add("onclick", "return false;");
Button3.OnClientClick = "decreaseProjHours(); return false;";
Button3.UseSubmitBehavior = false;
Thanks in advance,
Kokos

You have more or less the correct code in the line
Button3.OnClientClick = "decreaseProjHours(); return false;";
However the problem is that it looks for a javascript function decreaseProjHours(), which I'm assuming you don't have since you have that method on the server side in your code behind. OnClientClick is by definition a client-side handler and so the method needs to be defined on the client side. Since it can't find the javascript function, it fails to execute the next line return false;.
If you need that code to execute first and then return false to prevent postback, you need to put the code in a javascript function instead of in the code-behind. You can then have that fuction either return true or false if you wish, instead of having the additional return statement in the OnClientClick definition.
Note that if you have a server-side click handler defined as well, this won't execute if there is no postback; i.e. the server-side OnClick handler only executes if the client side returns true.

Related

How to get textbox value in ASP.NET click eventhandler

Somehow one of my stored procedures just stopped executing from aspx page. It works if I run it from SQL Server using EXEC. But when I click a button on my aspx page which assigns parameters and values, and launches this procedure, page reloads but data is not updated. This button can run create or update procedure, depending on the page parameters in the address bar. But nothing is executed.
In the aspx page I create that button like this:
<asp:Button id="btnSaveChanges" runat="server"
class="class_Button Normal Enabled"
OnClick="btnSaveChanges_Click" Text="Save changes" Width="100" />
Then in the code-behind file:
protected void btnSaveChanges_Click(object s, EventArgs e)
{
//if (Page.IsValid)
//{
SqlCommand sqlComm1 = new SqlCommand();
SqlConnection sqlConn1 = new SqlConnection("Server=localhost\\SqlExpress;Database=TestDB;Integrated Security=true");
sqlConn1.Open();
if(param_id == 0)
{
sqlComm1 = new SqlCommand("dcspCreateEmpDetails", sqlConn1);
}
if(param_id > 0)
{
sqlComm1 = new SqlCommand("dcspUpdateEmpDetails", sqlConn1);
}
sqlComm1.CommandType = CommandType.StoredProcedure;
if (param_id > 0)
sqlComm1.Parameters.AddWithValue("#empID", param_id);
sqlComm1.Parameters.AddWithValue("#empName1", tbName1.Text);
sqlComm1.Parameters.AddWithValue("#empSurname", tbSurname.Text);
sqlComm1.Parameters.AddWithValue("#empBirthDate", Convert.ToDateTime(tbBirthDate.Text));
sqlComm1.ExecuteNonQuery();
//}
sqlConn1.Close();
}
That's it. Page is valid, 100%. And even if I remove validation check, no result.
Here is the procedure:
CREATE PROCEDURE dcspUpdateEmpDetails
#empID int,
#empName1 nvarchar(50) = null,
#empSurname nvarchar(50) = null,
#empBirthDate datetime = null
AS
UPDATE Employees
SET
name_1 = #empName1,
surname = #empSurname,
date_of_birth = #empBirthDate
WHERE (employee_id = #empID)
Hope you'll help me with it, guys. I really don't understand what happened to this stuff...
Updates for the topic:
Examining debug messages I found, that textbox loses its text before the stored procedure in the OnClick event takes this text as a parameter.
Is it really normal that server first restores the page and only after that it executes code in OnClick event? I think it's logically incorrect because Page_Load is designed to load the default page, while buttons and other controls are used to change and manipulate content of a page. Why do I need those controls if their code can't execute timely?
I took my backup copy and copied all stuff regarding this problem to my current version. It was just the same absolutely identical code. I just replaced current code with the same code from backup and it works now. What was that?
I can't mark anything as an answer because there are only comments here. I'll mark this one.

MySqlDataAdapter failed to retrieve data on the first load

I use MySQL Connector for ASP.NET to retrieve data from my MySQL server. Everything seems to work fine, but just at the first asynchronous postback of my page, MySQLDataAdapter does not fill my DataSet. After a complete refresh the data is succesfully loaded by asynchronous postback.
I try to assign a bigger value to the command timeout, but it does not seem seem to work.
This does not happen locally, only on the production server.
I have checked that the fill does not work by displaying the request string and also by on each async postback (displaying the count() of my DS.table[0].rows).
This is really the fill method not working.
try
{
using (MySqlConnection conn = new MySqlConnection(_connexionString))
{
string requete = "";
DataSet DS = new DataSet();
requete = "SELECT * from MYTABLE";
using (MySqlDataAdapter MSDA = new MySqlDataAdapter(requete, conn))
{
DS.Clear();
MSDA.Fill(DS);
}
conn.Close();
conn.Dispose();
}
}
catch (MySqlException ex)
{
l_error.Text = ex.ToString();
}
Try putting code into Page_Init event too.
did you checked Page.isPostBack property ? may be you are not checking isPostback, properly. it would be helpful,if you share your entire method.
if(!Page.IsPostBack)
{
//load your datasets and data - adapters.
}
After few investigation in code, i found that it not work, in fact an value of request was empty ... so no data return by mysql server, there was session key which was expire...
thx all for your help !

Use of SqlCommandBuilder in ASP.NET

I have used the following code to add the feedback entered to the web form into a database.
The code works fine. But when I try to deleted thi statement
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
I am getting an error I mean it is executing the else part.
Can any one tell me what is the use of SqlCommandBuilder?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() == "")
{
Response.Write("<script>alert ('Name Field cannot be left blank')</script>");
return;
}
if (txtFeedBack.Text.Trim() == "")
{
Response.Write("<script>alert('FeedBack Field cannot be left blank')</script>");
return;
}
objSqlConnection.ConnectionString = connectionStringSetting;
objSqlConnection.Open();
try
{
SqlDataAdapter objDa = new SqlDataAdapter("select * from FeedBack", objSqlConnection);
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
DataSet objDs = new DataSet("FeedBack");
objDa.Fill(objDs, "FeedBack");
DataRow dr = objDs.Tables["FeedBack"].NewRow();
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;
dr[3] = txtCity.Text;
dr[4] = txtCountry.Text;
dr[5] = txtEmail.Text;
dr[6] = Convert.ToInt32(txtContactNo.Text);
dr[7] = txtFeedBack.Text;
objDs.Tables["FeedBack"].Rows.Add(dr);
objDa.Update(objDs, "FeedBack");
Response.Write("<script>alert('Your FeedBack has been submitted')</script>");
objSqlConnection.Close();
}
catch (Exception)
{
Response.Write("<script> alert('Error on Page. Please try after sometime')</script>");
objSqlConnection.Close();
}
And is there any way to display the specific error messages like if an user enters a string value instead of Integer value it should display the message as 'Input String not entered in correct format?
Never use catch (Exception). It hides the problem. If an exception is being thrown, then there's something serious wrong. You need to learn about it.
Remove the entire try/catch block (keep the code inside it!). Then run your code again. If there's an exception, then you'll see it on the error page. If not, then use the Event Viewer to look in the Windows Event Log for a warning message from the "ASP.NET" source. It should contain the complete exception.
Final answer is that the line you are talking out is doing a bunch of stuff in the background.
It is adding the insert, update and delete commands to the DataAdapter. So without it, you will crash and burn, unless you add those commands yourself to the DataAdapter.

Asp.Net SQL Refresh page duplicate inserts?

I have a *.aspx page that contains a text box and a button. When the user enters information in to the textbox and clicks post, it inserts the data into my sql database. The issue is, that if the user hits refresh, it will keep inserting the same data into the database. I am pretty sure the whole "click" method is called, not just the insert call. I tried messing with sessions but it complains. I am not really sure what to do. I am looking for a simple easy fix.
protected void PostButton_Click(object sender, EventArgs e)
{
string wpost = (string)Session["WallPost"];
DateTime wtime = (DateTime)Session["WallDateTime"];
if (txtWallPost.Text.Length > 0 && !wpost.Equals(txtWallPost.Text))
{
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO [WallTable] ([UserId], [FriendId], [WallPost]) VALUES (#UserId, #FriendId, #WallPost)";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
cmd.Parameters.AddWithValue("#FriendId", User.Identity.Name);
cmd.Parameters.AddWithValue("#WallPost", txtWallPost.Text);
conn.Open();
cmd.ExecuteNonQuery();
Session.Add("WallPost", txtWallPost.Text);
Session.Add("WallDateTime", new DateTime());
conn.Close();
txtWallPost.Text = "";
LoadWallPosts();
}
}
}
return;
}
If the PostButton_Click is the server handler for the click event on your button then insert code shold be executed only if the user hits the post button - it should not happen in case of refresh.
I am pretty sure is not enough - to be sure put a breakpoint in your PostButton_Click method, hit F5 to run in debug mode and see if the breakpoint gets hit with a refresh.
If so it means that:
you are calling explicitly
PostButton_Click from somewhere
else (Page_Load?)
PostButton_Click was accidentally
set as event handler for some other
event on the page
A quick way of verifying hypotesis 1 & 2 is to run a search for PostButton_Click and see where you are calling it from or if it set as handler for some other element (maybe your form?) in the markup.
Add Response.Redirect(Request.Url.ToString(), false); to your button event and that should solve the problem.
if he refreshes or press the back button the post will happen again, thus your page will process the same data thus insert once again.
You have to change your logic
It would be preferable to redirect the client to another page after the insert, however, if you really need the client stay in the same page, you can use a (bool) variable on your page to state if the insert has been done, and skip the insert logic if it has been executed before

UpdatePanel doesn't Refresh

I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.
I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method).
protected void gridViewDelete(object sender, GridViewDeleteEventArgs e)
{
bool bDelete = false;
bool bCheck = false;
if (hfControl.Value != "1")
{
// check relationship
bCheck = validation_method(.......);
if (bCheck)
{
bDelete = true;
}
}
else
{
hfControl.Value = "";
bDelete = true;
}
if (bDelete)
{
//process delete
}
else
{
string script = string.Empty;
script += " var x; ";
script += " x = confirm('are u sure?'); ";
script += " if (x){ " ;
script += " document.getElementById('hfControl').value = '1'; ";
script += " setTimeOut(__doPostBack('gridView','Delete$"
+ e.RowIndex + "'),0);";
script += " } ";
ScriptManager.RegisterClientScriptBlock(this,
Page.GetType()
, "confirm"
, script
,true);
}
}
On a postback, when the page loads is the view of the hidden field what was posted back or is it the value you set when the page loads? It may be that you have to worry about the case where in the postback you aren't resetting a value to what it was originally. Another point is that if you do a delete, are you refreshing the data that you show or is it the same? Those would be my suggestions.
When I do a postback the value is the same what was postedback. I think updatepanel wasnt refresh. I tried to do __doPostBack('UpdatePanel1',''), didnt work either.

Resources