how can I delete a row from gridview in code-behind page without using sqldatasource control?

Hi,

I have image button in my gridview. and I put its command name property 'delete'.

could you please tell me what code should I have in my code behind page to delete row?

I don't use sqldatasource for databound I use dataset.

I use VB for coding.

Thanks.

0
sepid
1/23/2009 1:03:17 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
2305 Views

Similar Articles

[PageSpeed] 28

Something like this: 

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
	If (e.CommandName.Equals("delete")) Then
		Dim btn As ImageButton = TryCast(e.CommandSource, ImageButton)

		If btn IsNot Nothing Then
			Dim row As GridViewRow = TryCast(btn.NamingContainer, GridViewRow)

			If row IsNot Nothing Then
				Dim shipperID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

				Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString)
				Dim cmd As New SqlCommand("DELETE [Shippers] WHERE ([ShipperID] = @ShipperID)", conn)
				cmd.Parameters.AddWithValue("ShipperID", shipperID)

				Try
					conn.Open()

					cmd.ExecuteNonQuery()
				Catch ex As Exception
					' Do something here
				Finally
					If conn IsNot Nothing Then
						conn.Close()
					End If
				End Try
			End If
		End If
	End If
End Sub

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
1/23/2009 1:25:23 PM

 in c#

protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
     string id = int.Parse(((Label)GridView2.Rows[e.RowIndex].Cells[1].FindControl("Label1")).Text.ToString());//find id of row
   try
        {
            SqlCommand dcmd = new SqlCommand("Delete tablename where id=@id", con);          
            dcmd.Parameters.AddWithValue("@id", id);
            dcmd.Connection.Open();
            dcmd.ExecuteNonQuery();
            dcmd.Connection.Close();
            msg = " Deleted Successfully !";
        }
        catch (Exception)
        {
            msg = "Error Occure";
        }
   }

0
tareshjha
1/23/2009 1:49:31 PM
Reply:

Similar Artilces:

code for Custom paging without using sqldatasource control and sql datasource control for gridview...........
 code for Custom paging without using sqldatasource control and sql datasource control for gridview...........i need code for how to show all pagenumbers in gridview with custom paging in gridview..............It is very urgent................................. T.Ashok Kumar  suppose that we have a table like thisCountryId  identity intCountryTitle    nvarchar(50)you can use this sql command for paging the dataUSE [CyberOffice]GO/****** Object:  StoredProcedure [dbo].[CountryGetListPaged]    Script Date: 09/17/2008 14:01:06 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[CountryGetListPaged]    @PageSize int,    @pageNumber int,    @TotalPageCount int out    @OrderBy VARCHAR(100) = NULL,    @OrderByDirection VARCHAR(20) = 'D'ASSET @OrderBy = COALESCE(@OrderBy,'CountryTitle')SET @OrderByDirection = COALESCE(@OrderByDirection,'D')IF LEN(@OrderByDirection) > 1  SET @OrderByDirection = UPPER(LEFT(@OrderByDirection,1))Declare @recordCount intDeclare @StartId intDeclare @EndId intSET TRANSACTION ISOLATION LEVEL READ COMMITTEDSELECT @recordCount = Count(*) FROM [Country]  IF (@PageSize <= 0)    SELECT @PageSize = 20SELECT @TotalPageCount = @recordCount / @PageSize + 1IF (@pageNumber > @TotalPageCount)    SELECT @pageNumber = 1SELECT @StartId = (@PageNumb...

Trying to use the FAQ " Sorting and paging in the GridView control when not using data source controls "Sorting and paging in the GridView control when not using..."
and I am not getting the results I had hoped for.  I keep getting a "Compiler Error Message: CS0123: No overload for 'AdhocJobGridView_PageIndexChanged' matches delegate 'System.EventHandler'".   Here is my event handling... protected void AdhocJobGridView_PageIndexChanged(object sender, GridViewPageEventArgs e){ try { AdhocJobGridView.DataSource = wsBaseInfoArray; AdhocJobGridView.PageIndex = e.NewPageIndex; AdhocJobGridView.DataBind(); }catch (Exception ex) {throw ex; }   Here is my aspx... <asp:GridView ID="AdhocJobGridView...

I can not send to a textbox control a string using page-behind-code if the control textmode property is set to password???
I am working on a intra-webapp using vb.net, and for some reason I can not send a string value to a textbox control when its textmode property is set to password.  Is there a way to accomplish this? Thanks,...

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 ...

Setting width for .net controls in code(.aspx) page using function call in code behind..
Hi,  Currently I am trying to set the width of the asp.net Table as follows. <asp:Table width="<%=GetWidth()%>" >   and code behind protected Unit GetWidth() { return Unit.Percentage(50); }     It's not working. I know that it works if I set the width complete on some page event(like page_load) of code behind....   Is there a way to maintain the same syntax like calling code behind function in design page...i.e. calling function of .aspx.cs in .aspx page and assign the width as shown above.   Thanks and regards, Giridhar...

Problem in Using DropDownList Control to select a selected row of SqlDataSource that is under GridView Control
Hi all,In my SQL Server Management Studio Express, I have a database "ChemDatabase" that has a table "LabData"  formatted in the following way: SampleID int PRIMARY KEY, SampleName nvarchar(25), ChemicalName, nvarchar(25), Concentration decimal(6.2) with 5 rows of records in this .dbo table. In my Visual Web Developer Express, I created a website "RPD-TCE" for extracting a row of record from the LabData table by using a DropDownList, a GridView and a SqlDataSource.  I want to click DropDownList to list one number of S...

can we use gridview control with in repeater control
HI all,     Can i use gridview control with in repeater control, Any one knows plzzz... let me know. Is there any possibility for this?      It is urgent required... plzzzz... help me..  ------------- ThanksBalu Chandaka  yes you can nest a gridview control in the repeater controlJeev~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~If you get the answer to your question, please mark it as the answer. Hi Jeev,    Thank you for your reply.But how can do that give some idea or If you have any example code snippet then plzzz... let m...

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 ID="GridEditSettlement" runat="server" AutoGenerateColumns="False" BackColor="Navy" BorderColor="IndianRed" BorderStyle="Solid" Font-Names="Verdana" Font-Size="X-Small" DataSourceID="SqlDataSource_grid" AllowPaging="True" AllowSorting="True" ForeColor="White" DataKeyNames="legid"> <Columns> <asp:CommandField ShowEditButton="True" CancelImageUrl="~/App_Graphics/quit.gif" CancelText="" EditImageUrl="~/App_Graphics/EditGrid.GIF" EditText="" UpdateImageUrl="~/App_Graphics/save.gif" UpdateText="" ButtonType="Image" /> <asp:BoundField DataField="StartDate" HeaderText="Start Date" ReadOnly="True" /> <asp:BoundField DataField="EndDate" HeaderText="End Date" ReadOnly="True" /> <asp:BoundField DataField="CounterpartDealRef" HeaderText="CP Deal Ref" ReadOnly="True" />   <asp:TemplateField HeaderText="Preliminary Settlement Price" ><ItemTemplate> <asp:Label ID=lblPreliminary runat=server ...

How to Edit & update & Delete a particular row of Gridview with code in c# & without using SQLDataSource
Hi Everyone           i have to take a gridview and to do the following operation              1)Insert new row in gridview by click on Add New Button in gridview            2)Edit that new row            3)Update that new row           4)Delete That new row how to write code for this.plz help thanks & regards rakesh    ...

How to delete row from GridView control
Hello,  I am working on an ASP.NET 2.0 app, and I am trying to wire up a "Delete" button to a gridview control on a form. Here is the code for the ASP :  <asp:GridView ID="gvInConditions" runat="server" AutoGenerateColumns="true" OnRowDeleting="gvInConditions_RowDeleting" DataKeyNames="Condition_ID" >         <Columns>                <asp:CommandField ButtonType="Button" SelectText=&...

ASPX Page Controls Are Not Hooking into Controls in Code Behind
The title says it all, but to be complete, here is a summary of the problem: I have a page that up until recently was correctly rendering and correctly attaching to the controls in the code behind. However, recently, after some code changes, the page no longer consistently does this. To make it more aggrevating the page will work correctly on some site installations and not others. I have not yet been able to determine the cause, nor a consistent replication. For example, Suppose MyPage.aspx has a control called txtFromDate which is an asp:textbox. The page's code behind is MyPa...

setting a controls properties within a master page from aspx page without code behind
I have a custom header control that has a public property TabID declared in the codebehind of the control itself. In asp1.1, I dragged the header control to a page and set the tabid like: <uc1:myheader runat="server" TabID="1" /> inside the aspx page it was placed. Now I would like to put the header control inside a master page, but I'm not sure how to set this property without setting it in codebehind for every page i create.  Is this possible? What is the best way to get this value to the header control as it is different for every page?...

Using gridview without the sqlDataSource control
Unfortunately, I must use the gridview without a sqlDataSource tag.  As I am discovering, much of the gridview functionality doesn't work without the  sqlDataSource tag, and must therefore be done by hand.  I have made some progress (I can bind the gridview to my database), and can get into edit mode,  but I'm having trouble with extracting the new values from the grid while in edit mode. Is there a  comprehensive example of how I would do this? I'd be very grateful for any and all help. Thanks very much!    hello friend, I have create a sample implementing Edit and Update Command of the GridView, refer to it all the codes added by hand <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewEdit.aspx.cs" Inherits="GridViewEdit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">    <div>    <asp:GridView ID="myGrid" runat="server" AutoGenerateColumns="false" OnRowCommand="myGrid_RowCommand" OnRowEditing="myGrid_RowEditing" OnRowUpdating="myGrid_RowUpdating">    <Columns>    <asp:TemplateField HeaderText="Edit"> ...

How can I access the property a control on a master page from the master page's code behind.
On my master page I have a label. I want to change this label's text property based on an element of the querystring. (label.text = "NewValue")All child pages using this master will display the same thing so I was trying to put the code in the master page so as not to have to duplicate it for the child pages or put it in a base class and use FindControl.Is it possible to access from a master page's codebehind the property of a server control that is placed on a master page's aspx? If so how?(I saw similar questions, but they all came from the view of a child accessing the property.)Thank you...

Page and Control Flashing Using AJAX Control Toolkit Controls
Page and Control Flashing Using AJAX Control Toolkit Controls I'm using IE7 and the ASP.NET AJAX Control Toolkit.  I'm using two controls -- Accordion and CollapsiblePanelExtender.  I'm actually using 2 CollapsiblePanelExtenders, and the Accordion control is inside one of the panels for the CollapsiblePanelExtender (see the code below). The problem I'm seeing is that when I click an Accordion pane to open/close it or click the CollapsiblePanelExtender panel to open/close the panels, the controls and page flash while the animation is in progess.  Everything else appears to be working except for this flashing. Would anyone know why this is happening and how to fix it?  My code is below.  Thanks in advance.   CSS.collapsiblePanelLeft{ height: 420px; overflow: hidden; width: 250px;} .collapsiblePanelSpacer{ background-color: #EEEEEE; cursor: pointer; height: 420px; width: 15px;} .collapsiblePanelRight{ height: 420px; overflow: hidden; width: 735px;} .accordionHeader{    background-color: #0000B8;    border: 1px solid Black;    color: White;    cursor: pointer; font-family: 'Trebuchet MS', Tahoma, Verdana, Arial, 'MS Sans Serif'; font-weight: bold;    padding: 0px;} .accordionContent{    background-color: #EEEEEE;    border: 1px dashed Black; ...

How to use FormView 's edit, cancel, insert and delete without using a control (Ex: sqldatasource, objectdatasource, etc..)?
I'm using C#, I cannot find any examples how to use edit, cancel, update, delete feature of the formview without using controls like objectdataSource/sqldataSource? I have 4 buttons (EDIT, SAVE, CANCEL, Delete), not sure how trigger the edit temple, insert template, etc... I would perfer to do it it programmatically. I would be grateful for any help!    if oyu want to change the Current Displayed Tempalte for the FormView , you can call FormView.ChangeMode as  follows:   ' put the FormView in edit mode FormView1.ChangeMode(FormViewMode.Edit)...

Can i use a view as the sqldatasource for a gridview control ?
Extreme newbie at this...But, in ASP.NET 2.0, the gridview, I want to use a sql view as the data source for my select, update and delete queries. I also have a solution for the insert using something i found on another web forum. I have it working for one table. But...i need to pull in other 'read only' display fields for the grid to have it make any sense to my users. Is a view the way to go with this? I am having issues with it updating--basically, it is not. Any guidance or examples on how to do this (basically joining two tables--can't believe that this would be that difficul...

Moving items from the page code behind to the user control code behind.
I am trying to setup a page with a user control specified as a header. Things work fine until the user control has to access dynamic content that is in the code behind of the main page. When I try to move these commands to the code behind for the user control I get errors saying items have not been declared. What is the best way to do this, I'm mainly trying to create some headers and footers for my asp.net project. if it belongs for the header move it to the headers code behind. It is probably saying items have not been declared because you moved the methods, but not the properties to...

How can I access a control on a master page from a user control using properties?
Hi, I have a master page which I'm using on my aspx page.  Within this aspx page is a user control and I would like to set a label on my master page using a value from my user control. I can do this using FindControl as shown below but I would like to use properties in my master page. The following code in my user control works perfectly: Label theFormName = (Label)this.Page.Master.FindControl("lblFormName");theFormName.Text = "My Test Form"; However I've been told that using properties is a much better ideas (errors would be picked up at compile time an...

Can't access my controls from a user control code behind
Helo All, I am creating this user control, and I just can't access the controls I have added to the user control from my code behind, I am using VS2005Tester Edition.. I have checked the designer class, and its not updated all the time with new controls information, any suggestions???? Thankssss What do you mean by cannot access the controls from code-behind - Visual studio doesn't show you intellisense or at runtime asp.net shows error? What i meant is that VS doesnt show the intellisense, which means that I can't access them in my codes...   ...

Using code-behind to access controls nested within atlas control
Hi,I wrote a simple ascx form and the wanted to wrap an accordian around it.  Trouble is that now my code-behind calls to the original controls can no longer access the control.  For example:<cc2:Accordion ID="Accordion1" runat="server" SelectedIndex="0" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" FadeTransitions="true" FramesPerSecond="40" TransitionDuration="250" AutoSize="None"><cc2:AccordionPane ID="AccordionPane1" runat="server"><Header><a href="">Required Fields</a></Header><Content><div class="logSection"><div class="logKeyData"><asp:ImageButton ID="btnUpload" runat="server" ImageUrl="~/Images/buttons/pngs/attach.png" />...</Content></cc2:AccordionPane></cc2:Accordion>code-behind:btnUpload.Attributes.Add("onMouseOut", "this.src='Images/buttons/pngs/attach.png'");These seems like quite a common scenario to me, so I'm sure you guys have thought of something Cheers,Mike. They are "hidden" another level deep.  You need to get a reference to them via the FindControl command.  Example: Dim CalendarRef As Web.UI.WebControls.Calendar CalendarRef = Me.AccordionPane2.ContentContainer.FindControl("Calendar1")  Use can now use C...

using controlS to control a gridview
This question is probably posted but i did not bother to look at 10,000+ posts so i am sorry. I've seen the tutorial where he builds a dataset and uses a gridview and controls the gridview with the drop down list box. What i am trying to do is to control the gridview with 2 drop down list boxes. First select the Country you life in and then the State. I've looked at the grid view properties but couldn't find where i can add another parameter. Is it possible to control a grid view (or any form of displaying the information) with more than 1 controller? Thank You.  ...

SqlDataSource Control and Gridview control
Hi, I'm new to web development and learning about these controls.  The books teach you to bind the gridview control to an sqldatasource to perform delete,update,insert functions as well as to list the records in a table.  Is this standard practice for real world applications?  Or is there another way that should be used to display/manage table data in the gridview control? Thanks. Tulsi Using a sqldatasource is the best way I know of for binding data to a gridview.  (I'm pretty new to web development too, so maybe someone else can chime in if they know someth...

How to get a handle on a user control from the code behind of the page holding the control?
I have a .aspx page that uses a .ascx page. So a web form with a server control(.ascx) on it. Basically the control has about four drop down listboxes on it. Lets call them ddlOne, ddlTwo, etc. My question, is how do I access the drop down listbox in the C# code behind file for my web form?(.aspx) So for example how would I access ddlOne which is the drop down listbox on the user/server control? Please help? You could expose them as read-only properties of the usercontrol.  In the codebehind of the usercontrol, you could add: Public ReadOnly Property DDL1() As DropDownList ...

Web resources about - how can I delete a row from gridview in code-behind page without using sqldatasource control? - asp.net.presentation-controls

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Using The LINQDataSource
-*+There is a new datasource control available in Visual Studio that works in much the same way as the SQLDataSource and the ObjectDataSource. ...

Gabriel Mongeon
Archive - Gabriel Mongeon

moredotnet
M ore d otnet .NET Interview Questions, ASP.NET, C#, VB.NET, XML, SQL Check Out http://www.dotnetUncle.com √ .NET NOTES OOPS in .NET .NET ...

Architectural Overview of the Windows Presentation Foundation Beta 1 Release
Introduction Windows Presentation Foundation Beta 1 Windows Integration New Features WinFX SDK Exploring the New Features Introducing "Express" ...

About Mikesdotnetting
I started this site as somewhere to store answers to bits and pieces that I see asked frequently in the forums at www.asp.net . Rather than type ...

Using MiniProfiler with SqlDataSource ASP.NET WebForms Control
public class ProfiledSqlDataSource : SqlDataSource{ protected override DbProviderFactory GetDbProviderFactory() { // get the "base" DbProviderFactory ...

ASP.NET Pivot Table - RadPivotGrid for ASP.NET AJAX
... reports. RadPivotGrid allows easy customization of all data reports. Try now! Use any declarative data source control (AccessDataSource, SqlDataSource, ...

Sign on
Sign On • Join • Forums Home User Name * Password * Remember me next time ( I forgot my password ) SUBMIT YOUR WTF Content Random Article All ...

ComboBox Sample
ComboBox is an ASP.NET AJAX control that, like the AutoCompleteExtender , combines the flexibility of a TextBox with a list of options that users ...

Resources last updated: 3/7/2016 11:09:08 PM