How To Edit Data In Gridview In Asp Net Using Command Prompt

-->

by Scott Mitchell

Download Sample App or Download PDF

With my present gridview code, please help me how to achieve the EDIT. //called on row edit command protected void gvSubDetailsRowEditing(object.com/gridview-inline-add-insert-edit-update-delete-data-in-asp-net-c-vb.html. 'alert('page updated sucessfully');window.location ='csrpage.aspx';',.

In the interfaces we've created so far, a user can accidentally delete data by clicking the Delete button when they meant to click the Edit button. In this tutorial we'll add a client-side confirmation dialog box that appears when the Delete button is clicked.

Introduction

Over the past several tutorials we ve seen how to use our application architecture, ObjectDataSource, and the data Web controls in concert to provide inserting, editing, and deleting capabilities. The deleting interfaces we ve examined thus far have been composed of a Delete button that, when clicked, causes a postback and invokes the ObjectDataSource s Delete() method. The Delete() method then invokes the configured method from the Business Logic Layer, which propagates the call down to the Data Access Layer, issuing the actual DELETE statement to the database.

While this user interface enables visitors to delete records through the GridView, DetailsView, or FormView controls, it lacks any sort of confirmation when the user clicks the Delete button. If a user accidentally clicks the Delete button when they meant to click Edit, the record they meant to update will instead be deleted. To help prevent this, in this tutorial we'll add a client-side confirmation dialog box that appears when the Delete button is clicked.

The JavaScript confirm(string) function displays its string input parameter as the text inside a modal dialog box that comes equipped with two buttons - OK and Cancel (see Figure 1). The confirm(string) function returns a Boolean value depending on what button is clicked (true, if the user clicks OK, and false if they click Cancel).

Figure 1: The JavaScript confirm(string) Method Displays a Modal, Client-Side Messagebox

During a form submission, if a value of false is returned from a client-side event handler then the form submission is cancelled. Using this feature, we can have the Delete button s client-side onclick event handler return the value of a call to confirm('Are you sure you want to delete this product?'). If the user clicks Cancel, confirm(string) will return false, thereby causing the form submission to cancel. With no postback, the product whose Delete button was clicked won't be deleted. If, however, the user clicks OK in the confirmation dialog box, the postback will continue unabated and the product will be deleted. Consult Using JavaScript s confirm() Method to Control Form Submission for more information on this technique.

Adding the necessary client-side script differs slightly if using templates than when using a CommandField. Therefore, in this tutorial we will look at both a FormView and GridView example.

Note

Using client-side confirmation techniques, like the ones discussed in this tutorial, assumes that your users are visiting with browsers that support JavaScript and that they have JavaScript enabled. If either of these assumptions are not true for a particular user, clicking the Delete button will immediately cause a postback (not displaying a confirm messagebox).

Step 1: Creating a FormView That Supports Deletion

Start by adding a FormView to the ConfirmationOnDelete.aspx page in the EditInsertDelete folder, binding it to a new ObjectDataSource that pulls back the product information via the ProductsBLL class s GetProducts() method. Also configure the ObjectDataSource so that the ProductsBLL class s DeleteProduct(productID) method is mapped to the ObjectDataSource s Delete() method; ensure that the INSERT and UPDATE tabs drop-down lists are set to (None). Finally, check the Enable Paging checkbox in the FormView s smart tag.

After these steps, the new ObjectDataSource s declarative markup will look like the following:

As in our past examples that did not use optimistic concurrency, take a moment to clear out the ObjectDataSource s OldValuesParameterFormatString property.

Since it has been bound to an ObjectDataSource control that only supports deleting, the FormView s ItemTemplate offers only the Delete button, lacking the New and Update buttons. The FormView s declarative markup, however, includes a superfluous EditItemTemplate and InsertItemTemplate, which can be removed. Take a moment to customize the ItemTemplate so that is shows only a subset of the product data fields. I ve configured mine to show the product s name in an <h3> heading above its supplier and category names (along with the Delete button).

With these changes, we have a fully functional web page that allows a user to toggle through the products one at a time, with the ability to delete a product by simply clicking the Delete button. Figure 2 shows a screen shot of our progress thus far when viewed through a browser.

Figure 2: The FormView Shows Information About a Single Product (Click to view full-size image)

Step 2: Calling the confirm(string) Function from the Delete Buttons Client-Side onclick Event

With the FormView created, the final step is to configure the Delete button such that when it s clicked by the visitor, the JavaScript confirm(string) function is invoked. Adding client-side script to a Button, LinkButton, or ImageButton s client-side onclick event can be accomplished through the use of the OnClientClick property, which is new to ASP.NET 2.0. Since we want to have the value of the confirm(string) function returned, simply set this property to: return confirm('Are you certain that you want to delete this product?');

After this change the Delete LinkButton s declarative syntax should look something like:

That s all there is to it! Figure 3 shows a screen shot of this confirmation in action. Clicking the Delete button brings up the confirm dialog box. If the user clicks Cancel, the postback is cancelled and the product is not deleted. If, however, the user clicks OK, the postback continues and the ObjectDataSource s Delete() method is invoked, culminating in the database record being deleted.

Note

The string passed into the confirm(string) JavaScript function is delimited with apostrophes (rather than quotation marks). In JavaScript, strings can be delimited using either character. We use apostrophes here so that the delimiters for the string passed into confirm(string) do not introduce an ambiguity with the delimiters used for the OnClientClick property value.

Figure 3: A Confirmation is Now Displayed When Clicking the Delete Button (Click to view full-size image)

Step 3: Configuring the OnClientClick Property for the Delete Button in a CommandField

When working with a Button, LinkButton, or ImageButton directly in a template, a confirmation dialog box can be associated with it by simply configuring its OnClientClick property to return the results of the JavaScript confirm(string) function. However, the CommandField - which adds a field of Delete buttons to a GridView or DetailsView - does not have an OnClientClick property that can be set declaratively. Kimi ni todoke live action sub indo. Instead, we must programmatically reference the Delete button in the GridView or DetailsView s appropriate DataBound event handler, and then set its OnClientClick property there.

Note

When setting the Delete button s OnClientClick property in the appropriate DataBound event handler, we have access to the data was bound to the current record. This means we can extend the confirmation message to include details about the particular record, such as, 'Are you sure you want to delete the Chai product?' Such customization is also possible in templates using databinding syntax.

To practice setting the OnClientClick property for the Delete button(s) in a CommandField, let s add a GridView to the page. Configure this GridView to use the same ObjectDataSource control that the FormView uses. Also limit the GridView s BoundFields to only include the product s name, category, and supplier. Lastly, check the Enable Deleting checkbox from the GridView s smart tag. This will add a CommandField to the GridView s Columns collection with its ShowDeleteButton property set to true.

How To Edit Data In Gridview In Asp Net Using Command Prompt

After making these changes, your GridView s declarative markup should look like the following:

The CommandField contains a single Delete LinkButton instance that can be accessed programmatically from the GridView s RowDataBound event handler. Once referenced, we can set its OnClientClick property accordingly. Create an event handler for the RowDataBound event using the following code:

This event handler works with data rows (those that will have the Delete button) and begins by programmatically referencing the Delete button. In general use the following pattern:

ButtonType is the type of button being used by the CommandField - Button, LinkButton, or ImageButton. By default, the CommandField uses LinkButtons, but this can be customized via the CommandField s ButtonType property. The commandFieldIndex is the ordinal index of the CommandField within the GridView s Columns collection, whereas the controlIndex is the index of the Delete button within the CommandField s Controls collection. The controlIndex value depends on the button s position relative to other buttons in the CommandField. For example, if the only button displayed in the CommandField is the Delete button, use an index of 0. If, however, there s an Edit button that precedes the Delete button, use an index of 2. The reason an index of 2 is used is because two controls are added by the CommandField before the Delete button: the Edit button and a LiteralControl that s used to add some space between the Edit and Delete buttons.

For our particular example, the CommandField uses LinkButtons and, being the left-most field, has a commandFieldIndex of 0. Since there are no other buttons but the Delete button in the CommandField, we use a controlIndex of 0.

After referencing the Delete button in the CommandField, we next grab information about the product bound to the current GridView row. Finally, we set the Delete button s OnClientClick property to the appropriate JavaScript, which includes the product s name. Since the JavaScript string passed into the confirm(string) function is delimited using apostrophes we must escape any apostrophes that appear within the product s name. In particular, any apostrophes in the product s name are escaped with '''.

With these changes complete, clicking on a Delete button in the GridView displays a customized confirmation dialog box (see Figure 4). As with the confirmation messagebox from the FormView, if the user clicks Cancel the postback is cancelled, thereby preventing the deletion from occurring.

Note

This technique can also be used to programmatically access the Delete button in the CommandField in a DetailsView. For the DetailsView, however, you d create an event handler for the DataBound event, since the DetailsView does not have a RowDataBound event.

Figure 4: Clicking the GridView s Delete Button Displays a Customized Confirmation Dialog Box (Click to view full-size image)

Net

Using TemplateFields

One of the disadvantages of the CommandField is that its buttons must be accessed through indexing and that the resulting object must be cast to the appropriate button type (Button, LinkButton, or ImageButton). Using 'magic numbers' and hard-coded types invites problems that cannot be discovered until runtime. For example, if you, or another developer, adds new buttons to the CommandField at some point in the future (such as an Edit button) or changes the ButtonType property, the existing code will still compile without error, but visiting the page may cause an exception or unexpected behavior, depending on how your code was written and what changes were made.

An alternative approach is to convert the GridView and DetailsView s CommandFields into TemplateFields. This will generate a TemplateField with an ItemTemplate that has a LinkButton (or Button or ImageButton) for each button in the CommandField. These buttons OnClientClick properties can be assigned declaratively, as we saw with the FormView, or can be programmatically accessed in the appropriate DataBound event handler using the following pattern:

Where controlID is the value of the button s ID property. While this pattern still requires a hard-coded type for the cast, it removes the need for indexing, allowing for the layout to change without resulting in a runtime error.

Summary

The JavaScript confirm(string) function is a commonly used technique for controlling form submission workflow. When executed, the function displays a modal, client-side dialog box that includes two buttons, OK and Cancel. If the user clicks OK, the confirm(string) function returns true; clicking Cancel returns false. This functionality, coupled with a browser s behavior to cancel a form submission if an event handler during the submission process returns false, can be used to display a confirmation messagebox when deleting a record.

The confirm(string) function can be associated with a Button Web control s client-side onclick event handler through the control s OnClientClick property. When working with a Delete button in a template - either in one of the FormView s templates or in a TemplateField in the DetailsView or GridView - this property can be set either declaratively or programmatically, as we saw in this tutorial.

Happy Programming!

About the Author

Scott Mitchell, author of seven ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, and writer. His latest book is Sams Teach Yourself ASP.NET 2.0 in 24 Hours. He can be reached at mitchell@4GuysFromRolla.com. or via his blog, which can be found at http://ScottOnWriting.NET.

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all I have a questions that looks hard / complex to me, and i know you can help me in this. Q { I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ..
using javascript getting value from textbox when edit button is clicked and both controls are present in gridview control
Hi All using javascript I want to get value from textbox when edit button is clicked and both controls that is texbox and button are present in gridview control .Alok Hi aloksinha83, Please see this post: http://forums.asp.net/t/1069245.aspx Thanks,Qin Dian TangMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help..
Issue with getting values from child controls in a gridview, to use for the update using a SQLDataSource control
Hi all, I have a gridview bound with a SQLDataSource. I am using the Update feature of the SQLDataSource to update a SQL Server database with values entered into the gridview. However I am not getting it to work. I believe this is due to the controls that contain the user entries are not the gridview itself, but rather child controls within the gridview. I have been using the names of the actual controls but nothing happens. Upon submit, the screen returns blank, and the database is not updated. Here is some code: <asp:GridView runat='server' AutoGenerate..
Datagrid(.net 1.1) to GridView(.net 2.0) and using the RowUpdating event how to extract the values from the controls.
Ok This is the settings: I use a Viewgrid with only itemtemplate colums for example. <asp:TemplateField HeaderText='Test'><ItemTemplate><asp:Label text='<%# DataBinder.Eval(Container.DataItem, 'Test1') %>' runat='server' meta:resourcekey='LBL_TestResource1'></asp:Label></font></ItemTemplate> <EditItemTemplate><asp:TextBox Text='<%# DataBinder.Eval(Container.DataItem, 'Test1') %>' Runat='server' meta:resourcekey='HDN_TestResource1' /></EditItemTemplate></asp:TemplateField> The ..
getting values from controls in gridview rows
hi there, i am building a simple shopping cart, i have a gridview with the products in. there is a bound field with the product id, a template field (with a table and a load of labels which are bound to the product details via an sql data source and gridviewrowdatabound) and a buttonfield which is the add to cart button. i am calling the rowcommand with the button field and need to get the product id from the boundfield and the quantity from a text box in the template field and write them to my data grid. this is the start of my code behind, the row index works perfectly, ..
get edit template control value in Gridview
I have a gridview that has two edit item templates which have controls textbox and a label I want to get the value of the controls when I update the gridview and add that to the update parameters. I keep getting object reference not set to an instance of an object for the label and the textbox. I cannot figure this out.I can't believe this has stumped me as I know I have done it before and it is very simple I must be over looking something. here is my vb here is my vb Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewU..
get values from a GridView without using for each row
hi guys, using asp.net's GridView is an advantage because it shows a pretty good view of your data.since i like reuse, i'd like to fetch the data from another GridViewthe only way i know to get the value is by using the For Each row . loop, but since i only need the selected one,For Each loop is not needed here in this case,is there any way to get the selected value of one GridView? see the picture below. thanks anyway. don't just accept influenceshttp://thedailyarr.tkhttp://www.ftpx.com/index.html Hi, try this protected void GridView1_SelectedIndexChanged(object..
Getting the row index of a command in gridview control
In my gridview I have a textbox and a save icon which allows a user to enter a date and click save which saves the date to the database for that record pointed to in the row. The problem I have is that I don’t know how to get the row to process the save in the codebehind. Normally I would set the command-argument equal to the product ID and then in the codebehind handle the event where the commandname matches the commandname for the save icon. I have the problem then though of not knowing which row caused the event. If I use a buttonfield, I know it sets the commandargument to the row index..
How do you get value from a control in GridView using a OnRowCommand?
In the GridView I have an OnRowCommand call that I use to highlight the selected row's background. But the main function is to get an id assigned to a label's text property and pass it to another method that build another gv as child set. Presently, it yells at me with a null exception error (System.NullReferenceException: Object reference not set to an instance of an object.) - can't handle this rejection.. I will kidly appreciate any help, here is the code:protected void gvCommodity_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName 'S..
get the row element values using row index for dynamic dropdownlist using javascript
Friends,How to get the row element values using row index for dynamic dropdownlist using javascript ?Thanks in advance I want creating dynamic dropdownlist using javascript. I am working on deleting a row. function DeleteRow(r) { var i = r.parentNode.parentNode.rowIndex;document.getElementById('ctl_Contentmain_tbldynamic').deleteRow(i);var str = document.getElementByName('ddljobs'); alert(str); } Check out this. var str = document.getElementById('<%=ddljobs.ClientID%>'); Thanks,santosh_maharajaPlease mark as answer ..
GridView
Hi all, I am trying to do what I thought would be a simple page but it is turning out to be challenging for me! I have a page with a GridView containing a bunch of offers that would be converted to orders. Say a sales rep submitted an offer through our purchasing system. This would be sent to my web page. The person who converts these offers would check my page to see what offers are waiting. They look up the order number on the purchasing system and check the offer is valid. If it is, they tick the box. This works fine as demonstrated here (feel free to..
Getting the textboxes to use to validate a control in the edit of a gridview
I have a gridview1 that has two fields, startdate and enddate, I turn both into template fields so I can drop in a validation control in the edit part of the edititemtemplate of the enddate. I can make it work comparing it to a static date, but I want to make sure its AFTER the begin date above. The question is, how do I get a hold of textboxstartdate when the only options I have in the drop-down for items to compare is textboxenddate? I've tried to squeeze in '((Textbox)DetailsView1.FindControl('textboxbegindate')) a bunch of different ways, but no luck. TIA&nbs..
Getting DataKey Value from a Row Using Checkboxes in GridView
Hi,I'm hoping someone can help me out with this. I've got a GridView, with a column of CheckBoxes that aren't bound to any data. After CheckBoxes are selected and a Button is clicked, I need to load a new page with more information about the rows that were checked. To do this I need the Primary Keys (integer ID values) of the selected rows, and I can't find a way to pull the Primary Keys from selected CheckBox rows without listing the ID's in the GridView itself.I'm trying to modify the code below (found online) to pull the DataKey (set as the Primary Key in the decla..
Is it possible to get cells value in row command in gridview?
Hi there, Is there any way to get the cells value in rowcommand. Because I have update command only. after updating I want to read those values and put it in textbox. I do not have select command. So Can any one please tell me how to read the cells value in Rowcommand? hi this wayProtected Sub RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView1.RowCommand For i As Integer = 0 To GridView1.Rows.Count - 1 'To get values from a Column 1Dim str As String = GridView1.Rows(i).Cells(0).Text ' if using some co..