ASP.NET Formview Item Inserting Event - asp.net

I'm using the FormView control in ASP.NET for a simple form to insert into a MS SQL DB. I have an event for onItemInserting to set some values behind (such as time stamp, etc) and was curious how to check some user entered values in the onItemInserting event and cancel the item from being inserted. The reason I want to do it in the code behind is to query the database and use the values to validate the user entered data.
Pseudo Code is as follows:
protected void Form_addRoom_ItemInserting(object sender, FormViewInsertEventArgs e)
{
... Query DB for some values ...
if(enteredMaxPeople > queryMaxPeople)
{
**Cancel** DB Insert
statusLabel.text = "Value entered not valid";
}
}
In the end the question comes down to how do I cancel a FormView from inserting in the code behind?
Thank you!
Sean

e.Cancel = true;

Related

Validation before inserting into Gridview

I am adding data in gridview but not using sql, and my question is i want to validate first if i already inserted the data in the gridview before inserting. searching every data in my gridview before inserting, is it possible?
It is possible, set asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" to this method, so when you click on insert it will execute this method, you can do the check before inserting:
Sample code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string val= textBox1.Text();
\\check if the value already exists in the datasource you are binding to gridivew <br/>
if(! value exists)
\\ do the insert
}

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.

ASP GridView All Rows In Edit Mode

In my ASP.NET page, I'm using a GridView to view data (Items & their prices). Currently users can edit the data (prices) in the grid row by row. (Click --> "Edit" link, change the values then "Update"). This is ROW by ROW. Is it possible to open all rows in Edit mode & use a single button (eg. Submit) to update all data once?
If you don't need to read only mode, in that case you can put input boxes ( textbox, dropdownlist, etc.) in ItemTEmplate section and bind them with existing data.
Next, put a submit button at above/below of the GridView and handle button Click event and loop through the GridView item data and save all database.
I'll post code block if you need. Thanks for your time.
And you will have better control on that you doing by using listview instead of gridview.
My best practise is using listview and custom web user control for this kind of problems.
If you fill your listview with your user control, you will easy to manage your saving method, just have to iterate on the listview items, find control and call your Save() method for each item.
I know that this question has already been answered but here is the code for loop through the GridView getting data and store it in the Data Base:
Using libraries:
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.Odbc;
Code Behind:
// this is a variable that have the Query or SQL Commands.
string DataBaseQuery = "UPDATE [table] SET [variable2] = #variable2, [variable3] = #variable3) WHERE [variable1] = #variable1";
//Click Event from a LinkButton.
protected void LinkButton1_Click(object sender, EventArgs e)
{
//"ConnectionString" its the string connection for your DataBase (often get from the WebConfig File or a DataSource element.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
//this is for open the database using the string connection.
connection.Open();
//this is the algorithm for going through the entire GridView.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//"DataBaseQuery" it's a string variable that have the Query or SQL Commands.
SqlCommand cmd = new SqlCommand(DataBaseQuery, conexion);
//this case it's for obtain the text variable of the first column of the gridview (in my case it was the ID of the register).
cmd.Parameters.AddWithValue("#variable1", ((Label)GridView1.Rows[i].Cells[0].FindControl("Label1")).Text.ToString());
//this case it's for obtain the selected value of a DropDownList that were in the 14 th column)
cmd.Parameters.AddWithValue("#variable2", ((DropDownList)GridView1.Rows[i].Cells[15].FindControl("DropDownlist2")).SelectedValue.ToString());
//this command it's for obtain the text of a textbox that is in the 15 th column of the gridview.
cmd.Parameters.AddWithValue("#variable3", ((TextBox)GridView1.Rows[i].Cells[16].FindControl("TextBox17")).Text.ToString());
cmd.ExecuteNonQuery();
}
//after going through all the gridview you have to close the connection to the DataBase.
connection.Close();
}
}
Of course you have to adjust the code to your particular case but it's very easy. In this code you have the example to obtain values for other object like labes, textbox and dropdownlist in the gridview.
I suffered a lot to make run this code (I'm not good programming) but I'm happy to help.
NOTE: For count the columns of the gridview you have to start at zero.
NOTE2: Sorry for my bad English by the way... It's not my nature language.

Assigning a session variable into DetailsView

I have a Session Variable declared and checked that it exists. I would like the DetailsView to display the Session Variable number in the INSERT Textbox in the DetailsView. When the Insert Button is pressed I, require the record in the DetailsView to be despatched to the database, to create an additional record.
From the experimentation I have carried out, it appears to be difficult to penetrate the DetailsView. I imagine that there is a requirement for some "Code Behind" to be included.
You need to use the detailsview Databound event and assign the value to the textbox. e.g.
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
TextBox TextBox1 = DetailsView1.FindControl("TextBox1") as TextBox;
TextBox1.Text = Session["Name"].ToString();
}
}

How to retain field values on error in a dynamic gridview?

I have a page which has a GridView on it, which is populated from a database. Some of the columns in the GridView have text boxes, as well as Checkboxes.
When the user saves the page, the page may error if they have not entered their data correctly. At this point, I need to re-display what they have entered already so they can simply make the correction instead of having to change everything from scratch again.
The part that I'm having trouble with is the fact that this GridView can have a variable number of rows, so in turn a variable number of fields. What would be a good way to retain those values?
e.Cancel = true; will do the trick
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true;
//Display Message here
}

Resources