I have an application that makes the user chose an item from a list, then the components of this item are displayed and when clicking a component, a dataGridView is populated with the stock of that component (size and quantity).
I'd like to make it so that the user can modify the numbers in the dataGridView and UPDATE, INSERT and DELETE inside the database by only using only one "Save" button.
I managed to make these functions work separately but I wonder how it is possible to have them all in one button_click event.
For example here's my update function :
private void buttonSave_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
if (con.State == ConnectionState.Open)
{
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
SqlCommand update = new SqlCommand("UPDATE stock_test SET quantity=" + row.Cells[1].Value + " WHERE size=" + row.Cells[0].Value+ "AND codeArticleComponent ='" +labelComponentChosen.Text+ "'" , con);
update.ExecuteNonQuery();
update.Parameters.Clear();
}
}
}
}
edit : I know the older version of this application managed this by simply dropping the whole table and inserting all the values again but I don't want to do it like this because it seems totally unsafe and the table will end being of a big size.
Sometimes there is a need to insert, update and delete records in a GridView using a single Stored Procedure instead of creating separate Stored Procedures for each operation.
Suppose I have one .aspx web page in which I need a to insert, view, update and delete records. To do that, instead of creating four Stored Procedures to perform these tasks I will create a single Stored Procedure to satisfy my requirements and I will access it in code behind depending on the action performed by the end user on a button click.
I have written this article specially focusing on newcomers and anyone new wants to insert, update and delete records in a GridView using a Single Stored Procedure, so let us start with a basic introduction.
First create the the table named employee as:
I have set the primary key on the id column and I have set the Identity specification to Yes.
Now we have a table to perform these operations for. Now let us start to create the Stored Procedure.
The Stored Procedure is created using the keyword Create Procedure followed by the procedure name. Let us create the Stored Prcedure named "EmpEntry" as in the following:
create Procedure EmpEntry
(
--variable declareations
#Action Varchar (10), --to perform operation according to string ed to this varible such as Insert,update,delete,select
#id int=null, --id to perform specific task
#FnameVarchar (50)=null, -- for FirstName
#MName Varchar (50)=null, -- for MName
#Lname Varchar (50)=null -- for LastName
)
as
Begin
SET NOCOUNT ON;
If #Action='Insert' --used to insert records
Begin
Insert Into employee (FirstName,MName,LastName)values(#Fname,#MName,#Lname)
End
else if #Action='Select' --used to Select records
Begin
select *from employee
end
else if #Action='Update' --used to update records
Begin
update employeeset FirstName=#Fname,MName=#MName,LastName=#Lname where id=#id
End
Else If #Action='delete' --used to delete records
Begin
delete from employeewhere id=#id
end
End
The comments in the Stored Procedure above clearly explain which block is used for which purpose, so I have briefly explained it again. I have used the #Action variable and assigned the string to them and according to the parameter ed to the Stored Procedure the specific block will be executed because I have kept these blocks or conditions in nested if else if conditional statements.
The most important thing is that I have assigned null to each variable to avoid the effect on the parameter ed to the Stored Procedure because we are ing a different number of parameters but not the same number of parameters to the Stored Procedure to perform these tasks.
Now create the one sample application "Empsys" as:
"Start" - "All Programs" - "Microsoft Visual Studio 2010".
"File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page).
Provide the web site a name such as "Empsys" or another as you wish and specify the location.
Then right-click on Solution Explorer - "Add New Item" - "Default.aspx page".
Drag and drop one button, three textboxes, one GridView and one hidden field to the hidden value to the database and one label on the section of the Default.aspx page.
Then switch to the design view; the section of the Default aspx page source will look as in the following:
<form id="form1"runat="server">
<div>
First Name <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Middle Name<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
Last Name <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:ButtonID="Button1"runat="server"Text="save"onclick="Button1_Click" />
</div>
<asp:HiddenField ID="HiddenField1" runat="server"/>
<asp:GridViewID="GridView1"runat="server" >
</asp:GridView>
</form>
Now use the following GridView event properties to perform events such as update, delete, edit cancel and so on. Let us see what the properties are:
DataKeyNames: This property I have used to the the row index of GridView
OnRowEditing: This property is used to handle the event when the user clicks on the edit button
OnRowCancelingEdit: This property is used to handle the event when the user clicks on the Cancel button that exists after clicking on the edit button
OnRowDeleting: This property is used to handle the event when the user clicks on the delete button that deletes the row of the GridView
OnRowUpdating: This property is used to handle the event when the user clicks on the update button that updates the Grid Record
Now my grid will look such as the following:
<asp:GridViewID="GridView1" runat="server" DataKeyNames ="id"OnRowEditing ="Edit"
OnRowCancelingEdit ="canceledit" OnRowDeleting ="delete" OnRowUpdating = "Update" >
</asp:GridView>
On the preceding GridView properties I have assigned the method name to be called for particular operations.
Method to Insert Data in Database
Right-click from the design page and view the code and then write the following code in the default.aspx.cs page to save the inserted records in the database:
protected void empsave(object sender, EventArgs e)
{
connection();
query = "studentEntryView"; //Stored Procedure name
SqlCommand com = new SqlCommand(query, con); //creating SqlCommand object
com.CommandType = CommandType.StoredProcedure; //here we declaring command type as stored Procedure
/* adding paramerters to SqlCommand below *\
com.Parameters.AddWithValue("#Action", HiddenField1.Value).ToString();//for ing hidden value to preform insert operation
com.Parameters.AddWithValue("#FName",TextBox1.Text.ToString()); //first Name
com.Parameters.AddWithValue("#Mname ", TextBox2.Text.ToString()); //middle Name
com.Parameters.AddWithValue("#LName ",TextBox3.Text.ToString()); //Last Name
com.ExecuteNonQuery(); //executing the sqlcommand
Label1.Visible = true;
Label1.Text = "Records are Submitted Successfully";
}
Now create the mehtod to view the records in the GridView:
public void viewdata()
{
connection();
query = "studentEntryView";
SqlCommand com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Action", HiddenField2.Value).ToString();
DataSet ds =new DataSet();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
The following is method for the "OnRowEditing" Event:
protected void edit(objectsender, GridViewEditEventArgs e)
{
GridView1.EditIndex= e.NewEditIndex;
gedata();
}
The following is method for the "OnRowCancelingEdit" Event:
protected void canceledit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gedata();
}
The following is method for the "OnRowDeleting" Event:
protected void delete(object sender, GridViewDeleteEventArgs e)
{
connection();
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
HiddenField1.Value = "Delete";
query = "EmpEntry";
com = new SqlCommand(query, con);
com.CommandType =CommandType .StoredProcedure;
com.Parameters.AddWithValue("#Action", HiddenField1.Value).ToString();
com.Parameters.AddWithValue("id", SqlDbType.Int).Value = id;
com.ExecuteNonQuery();
con.Close();
gedata();
}
The following is method for the "OnRowUpdating" Event:
protected void update(object sender, GridViewUpdateEventArgs e)
{
connection();
int id=int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
HiddenField1.Value = "update";
query = "EmpEntry";
com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Action", HiddenField1.Value).ToString();
com.Parameters.AddWithValue("#FName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());
com.Parameters.AddWithValue("#MName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());
com.Parameters.AddWithValue("#LName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());
com.Parameters.AddWithValue("#id", SqlDbType.int ).Value = id;
com.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
gedata();
}
Brief introduction to the code
In the sample code above I have used the two string queries for giving the Stored Procedure name and the constr for storing the connection from the web.config file and another thing is that I have used a hidden field by which I am ing the action values that are required to our Stored Procedure.
Now our application is ready to use, press F5 or other as you know, then enter the some values to TextBox and press the "Save" button.
Now after clicking on the "Save" button, the hidden field value takes the value "Insert" and es it to the Stored Procedure as the action and because of this the Stored Procedure will execute a particular type of block.
Now at page load I have called the method, so after that the grid will fill as in:
Now click on the Edit button that calls the edit method as shown in the following grid:
If you click on the "Cancel" button then the editcancel method will be called and edit mode will be cancelled. Now enter some values into the grid TextBox and click on an update button that calls the update method and then the records in the GridView will be updated as in:
Now click on the delete button that calls the delete method and deletes the records from the GridView
Note
For detailed code please download the zip file attached above.
Don't forget to update the Web.config file for your server location.
Related
I have a webpage called blogwebsite and in that I have a textbox and search button. I am passing the value of textbox on button click to another webform called blogseacrh through session. I also have a database bound through these webforms. In this blogsearch webpage I have taken the session variable in a textbox. Using this textbox value I am writing a oledbcommand select query. I am fetching data from the database using this textbox value and want to display it on the blogsearch webpage. For this to happen I am using oledbdatareader to read the data and then write the fetched data in the textbox. But when I am running the webpage when I click on search button it gives me the error at the oledbdatareader line saying that no given value given for one or more required parameters.
I really can't understand what I am doing wrong. Can someone please give me a solution?
This is the button click event which is working perfectly
protected void btn_srch_Click(object sender, EventArgs e)
{
Session["name"] = txt_bnm.Text;
Response.Redirect("blogseacrh.aspx");
}
This is the code that needs to be executed on another webpage on button click event
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
con.Open();
txt2_bnm.Text = Session["name"].ToString();
cmd = new OleDbCommand("select user from tbl_blogs where book_name='" + txt2_bnm.text + "',con); `
OleDbDataReader d = cmd.ExecuteReader();
while (d.Read())
{
user = d["user"].ToString();
Response.Write(user);
}
cmd = new OleDbCommand("select blogs from tbl_blogs where book_name='" + txt2_bnm.Text + "' ", con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
blogs = dr["blogs"].ToString();
Response.Redirect(blogs);
}
con.Close();
}
I have also checked all the field names and table name and they are all correct as well.
Can someone please solve this error. i have an assignment to complete please.
So I'm making a seat reservation system for a school project and I'm stuck. I'll explain exactly what I'm trying to do. I created this form:
Seat Reservation Layout
As you can see, I created a seat layout. All the seats are buttons. I also created a local SQL database with SeatID (which matches the names of the buttons exactly) and Availability (either True or False).
What I wanted to do is let the user choose seat(s) (which becomes green after clicking on it) and whenever the user clicks on the "OK" button, the seats get reserved, meaning that I want the Availability in my database corresponding with the buttonname and thus, the SeatID, to become False (meaning the seat got reserved). After running the program again, the reserved seats need to be red, on the start, meaning they can not get reserved.
So basically I managed to do it all; My database works, reserved seats are red whenever I run the program etc.
The only thing I can not get working is updating the database with reserved seats.
private void OK_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
command = new SqlCommand(sql, con);
foreach (Button button in buttons)
{
if (button.BackColor == Color.Green)
{
sql = "UPDATE Seats SET Availability='" + "False" + "'WHERE SeatID=" + button.Name;
adapter.UpdateCommand = new SqlCommand(sql, con);
adapter.UpdateCommand.ExecuteNonQuery();
}
}
command.Dispose();
con.Close();
}
Above you see my code where I try to update the databse. I made the list of all buttons called "buttons" and the code above looks through all the buttons and checks whether they're green or not (green == clicked, so ready to be reserved). That is supposed to happen when I click on the "OK" button. When I run this, I get this error message:
Error Message
So, what am I doing wrong? How am I supposed to update the database by checking whether the SeatID corresponds with the button name?
Thanks in advance.
EDIT: Here I attach my database:
Datatable
Data
You should use parameters in your SQL query insead.
sql = "UPDATE Seats SET Availability= #Availabe WHERE SeatID = #SeatID" ;
adapter.UpdateCommand.Parameters.AddWithValue("#Available", false); //I assume that your Availibility column is a BIT type.
//If a varchar column for exemple, you can use
//adapter.UpdateCommand.Parameters.AddWithValue("#Available", "False"); //But, you should use a bit column instead.
adapter.UpdateCommand.Parameters.AddWithValue("#SeatID", button.Name);
adapter.UpdateCommand = new SqlCommand(sql, con);
adapter.UpdateCommand.ExecuteNonQuery();
To add parameters to your SQL Command, you can take a look at this :
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8
Did you try this command;
sql = "UPDATE Seats SET Availability='False' WHERE SeatID=" + button.Name;
I am using ASP.NET 4.5 C#
I have a FormView in Insert mode, linked to an MSSQL database, with 2 hidden fields in it.
These fields are populated when the page loads.
I now need this data to be inputted to the database automatically without anyone having to click on an insert button.
How do I achieve this once the data has bound?
Here is the code I have been trying, it's working except the adnumber value is not uploading, only the date
protected void FormView1_DataBound(object sender, EventArgs e)
{
string ad, insertqry;
ad = ((HiddenField)(FormView1.FindControl("Adnumber"))).Value;
DateTime hit = DateTime.Now;
insertqry = "insert AdvertsHits(ad,hit) values(#ad,#hit)";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand(insertqry, con);
cmd.Parameters.Add("#ad", SqlDbType.VarChar, 250).Value = ad;
cmd.Parameters.Add("#hit", SqlDbType.DateTime).Value = hit;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
Write a method to insert data into data base and call that method after hidden fields get the data, then data automatically inserted into database.
I have a C# winforms app form with a TreeView on it. Populating the TreeView is done using a stored proc and view (not table) from database.
This works fine as it puts the information into the TreeView as all root nodes. I have drag and drop available to the users for the TreeView so they can move nodes and have a parent/child/grandchild/etc. However, many are needed. This also works fine.
What I am struggling with (more like getting frustrated with) is saving the users' TreeView changes back to the database table. I considered making the change with each move but decided to use a button click event when all is done being moved.
I am providing what code I have so far. Just remember that this is not final look of the click event since button is not named plus a few other cleanups needed as well and the sqlUpdate will actually become a stored proc.
In the sqlUpdate there are 2 parameters listed; #parentid and #industryid. If I was to hard code those with a number (ex: 1 and 4) the update works and makes the changes in the table to the correct industry id. When the TreeView is populated it uses three (3) fields from the table; IndustryID, ParentID, IndustryItem. These go into a datatable and to the TreeView.
What I am getting frustrated over is getting the #parentid and #industryid which is why I am posting here for help. I've done updates, deletes, inserts many times but for some reason this is making draw a blank.
I do realize I need to specify the parameters in the code but I'm thinking that is where the issue is. Here are the 2 lines;
command.Parameters.AddWithValue("#parentid", ?????);
command.Parameters.AddWithValue("#industryid", ?????);
And here is the click handler:
private void button6_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand();
{
string sqlUpdate = "UPDATE tblIndustry SET IndustryItemParentID = #parentid WHERE IndustryID = #industryid";
try
{
conn.Open();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = sqlUpdate;
command.ExecuteNonQuery();
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show("There is an error." + '\r' + '\n' + '\r' + '\n' + ex.ToString(), "NOTICE", MessageBoxButtons.OK);
}
finally
{
conn.Close();
}
}
}
}
Here's one way to do it:
For #industryid, use an auto-incremented id column in the database. Assign that value to the treeview node tags when you populate the treeview. Then use the value of treeview.parent.tag for #parentid.
I've got a gridview displaying product instance info; I need a hyperlink in my Action column to bring up an view/edit page that displays the row data. How do I make the link bring up the data from that specific row into the edit page?
Note: there are other questions with similar titles, however, they do not cover this specific topic.
Use datakeys in the gridview, using datakey will get you the id of each clicked hyperlink , and then you can use that id to edit or delete the selected items easily. In the code behind just find the hyperlink control , pass the data key and write d update sql for it. Inorder to move your data to other pages you can sessions but if you are developing a commercial website session wont be a good idea due to its security issues, use cookies in that case .
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["productID"] != null)
{
productID = Convert.ToInt32(Request.QueryString["productID"]);
bindData(productID)
}
...
}
}
protected void bindData(int productID)
{
//to avoid sql injection as mentioned below use parameters
SqlConnection conn = new SqlConnection(ConnectionString); // define connection string globally or in your business logic
conn.Open();
SqlCommand sql = new SqlCommand("Select * From [Table] Where ID = #productID",conn);
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#ID";
parameter.Value = productID;
sql.Parameters.Add(parameter);
conn.close()
}
You can also use Microsoft.ApplicationBlocks.Data.dll to avoid repeating ado.net , it will reduce your code.
Try something like this?
ViewProducts.aspx:
<columns>
<asp:HyperLinkField DataNavigateUrlFields="ProductID" HeaderText="Edit"
ItemStyle-Width="80"
DataNavigateUrlFormatString="EditProduct.aspx?productID={0}"
Text="Select" ItemStyle-HorizontalAlign="Center" />
...
</columns>
EditProduct.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["productID"] != null)
{
productID = Convert.ToInt32(Request.QueryString["productID"]);
...
}
...
}
}
There are n+1 ways to solve this problem. If you are using the sql data source you can accentually have VS generate the sql and edit logic for you if you don't have specific requirements. here is a code project tutorial.
Another oft used tactic is to add a command button to the row and populate the command argument with the ID of the row you want to edit then in the oncommand event handle what ever logic you need.
you can also use a simple html link and and use get parameters. Or you can session like I said there a a ton of ways to solve this problem.