How to determine the row number when clicking a delete button I added to a template column from a GridView control???

Hello all,

I am working using the codebehinde the page with VB.NET 2005 (web application).  I have a gridview where I added a template column, inside that templated column I added a delete button.  I would like to know how could I determine which row number corresponds to the clicked button so I can delete the current record.

This is what I have:


 
Protected Sub LinkButtonDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)


        Try

            Dim cmd As SqlCommand
            Dim objConnection As SqlConnection
            objConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("GDBRemitanceConnectionString1").ConnectionString)
            Dim MySQL As String = "DELETE from CCD WHERE (Id6 = @Id6)"

            cmd = New SqlCommand(MySQL, objConnection) 'To update user records.
            With cmd.Parameters

                Session("@Id6") = Me.GridView1.SelectedRow.Cells(1).Text' this doesnt work because when I clic the delete button I doesnt select the current row, so I get a reference error. .
                MsgBox(Session("@Id6"))

                .Add(New SqlParameter("@Id6", Session("@Id6")))

            End With

            ' Open the connection, execute the command, and close the connection.

            objConnection.Open()
            cmd.ExecuteNonQuery()
            objConnection.Close()
            Me.lblMsg.Text = "Record has been deleted."

            'Once deleted returns to Main BusinessUnits Page.
            Response.Redirect("BusinessUnits.aspx")
        Catch

            Me.lblMsg.Text = "The record could not be deleted for security reasons."

        End Try


    End Sub
 
I need to know how to determine the current row index in order to delete the record.

Thanks,
0
mendez_edd
8/14/2006 6:16:47 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

10 Replies
950 Views

Similar Articles

[PageSpeed] 37

Sure, set the LinkButton.CommandArgument to the GridViewRow.RowIndex beforehand, and you can extract it later like this:
 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
	GridViewRow gvr = e.Row;

	switch (gvr.RowType)
	{
		case DataControlRowType.DataRow:
			{
				// Retrieve controls
				LinkButton link1 = gvr.FindControl("link1") as LinkButton;


				if (link1 != null)
				{
					// Set row index
					link1.CommandArgument = gvr.RowIndex.ToString();
				}


				break;
			}
	}

}

protected void link1_Click(object sender, EventArgs e)
{
	// Retrieve control
	LinkButton link1 = sender as LinkButton;

	int rowIndex = Int32.Parse(link1.CommandArgument);
}
 
Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
8/14/2006 6:48:54 PM
Sorry,  I havent work with C#, but thanks anayways, I will try to convert it.

If anyone can give me a VB.NET equivalent I will appreciate it too.

Thanks,
0
mendez_edd
8/14/2006 7:28:26 PM
What does grv means?

 '    GridViewRow gvr = e.Row
0
mendez_edd
8/14/2006 7:32:40 PM
That's just the name of the variable.

Dim gvr As GridViewRow = e.Row

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
8/14/2006 8:23:42 PM
I tried converting it to VB.net using
http://www.developerfusion.co.uk/Utilities/convertcsharptovb.aspx

this is what I got:


 
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
 Dim gvr As GridViewRow = e.Row
 Select gvr.RowType
 Case DataControlRowType.DataRow
   Dim link1 As LinkButton = CType(ConversionHelpers.AsWorkaround(gvr.FindControl("link1"), GetType(LinkButton)), LinkButton)
   If Not (link1 Is Nothing) Then
     link1.CommandArgument = gvr.RowIndex.ToString
   End If
   ' break
 End Select
End Sub

Protected Sub link1_Click(ByVal sender As Object, ByVal e As EventArgs)
 Dim link1 As LinkButton = CType(ConversionHelpers.AsWorkaround(sender, GetType(LinkButton)), LinkButton)
 Dim rowIndex As Integer = Int32.Parse(link1.CommandArgument)
End Sub
 

I still do not get it.  I am getting grammar error for  line containing : ConversionHelper.AsWorkaround, 'never  heard of this before.

Thanks for any suggestions.
0
mendez_edd
8/14/2006 8:32:17 PM
 
	Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
		Dim gvr As GridViewRow = e.Row

		Select Case gvr.RowType
			Case DataControlRowType.DataRow
				Dim link1 As LinkButton = CType(gvr.FindControl("link1"), LinkButton)

				If Not link1 Is Nothing Then
					link1.CommandArgument = gvr.RowIndex
				End If
		End Select
	End Sub

	Protected Sub link1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles link1.Click
		Dim link1 As LinkButton = CType(sender, LinkButton)

		Dim rowIndex As Integer = link1.CommandArgument
	End Sub
 
Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
8/14/2006 9:02:46 PM

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton tb = (LinkButton)e.Row.Cells[1].FindControl("link1");
          if(tb!=null)

               {tb.CommandArgument = ((GridViewRow)e.Row).RowIndex;

               }
        }
        e.Row.RowState = DataControlRowState.Insert;
        Response.Write(e.Row.Cells[0].);

    }

Protected void link1_Click(object sender , System.EventArgs e

  {

 LinkButton link1=(LinkButton)sender;
  int index= link1.CommandArgument;
}




Best Regards,
__________________________________________________
Sincerely,
Rex Lin
Microsoft Online Community Support

This posting is provided "AS IS" with on warranties, and confers no rights.
0
rexlin
8/15/2006 1:56:59 AM
I tried the code provided by ecbruck.  I am getting an error at:

Protected Sub link1_Click  where it says " Handle Link.Click"  This is the tooltip error I am getting:
"Handles clause requieres a WithEvents variable defined in the containing type or one of its base types"

again, This is a New Column I added to a GridView and I inserted a linkbutton inside of it.  That button is going to be a delete record button,  The problem is that I need to tell what is the row number corresponding to the delete button I have clicked.

Thanks for suggestions,
0
mendez_edd
8/15/2006 4:43:48 AM
Got it!

Thanks all!


 
 Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim gvr As GridViewRow = e.Row

        Select Case gvr.RowType
            Case DataControlRowType.DataRow
                Dim link1 As LinkButton = CType(gvr.FindControl("link1"), LinkButton)

                If Not link1 Is Nothing Then
                    link1.CommandArgument = gvr.RowIndex
                End If
        End Select
    End Sub

    Protected Sub link1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim link1 As LinkButton = CType(sender, LinkButton)

        Dim rowIndex As Integer = link1.CommandArgument
    End Sub
 
0
mendez_edd
8/15/2006 4:59:03 AM

 Hey Thanks u very much ecbruck , this one is nice logic..

0
rohitjpuranik
11/10/2008 9:24:26 AM
Reply:

Similar Artilces:

How to delete controls in GridView when the delete button in a row is clicked
Hi,   I am having issues with my gridview.....i added 2 dropdown and 2 compare validators....whenever i delete a row though......the dropdown and compare validators are becoming null........thus when i click a button, it is still validating.............anyway to delete this when i click the delete button or even handle?   Please help.  ...

Adding row (one at a time) in gridview on a button click. And cells of added row should contain controls like DROPDOWN LIST or TEXT BOX.
Dear Friends, I am in great need for the solution/hints/guidance of my requirement, if anyone can help with.  Let me explain what I need."I need a Gridview control on a webpage having following 5 columns/fields.     Column 1: It just has a "+" button in its header only (other cells for this column is empty)    Column 2: The Column header here is "FIELD" and  it should contain dropdown list (which is populated from some database)    Column 3: The Column header here is "Operator" and  it should ...

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

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

Controlling a variable numbers of controls dynamically added to a user control
 Ok, thinking caps on people, this has been causing me grief for a couple of days now. I have an .aspx page which contains various user controls housed in an Accordion control from the Ajax Toolkit and lots of UpdatePanels, these user controls all interact with each other through the parent page, e.g clicking buttons in one control effects visibility of other controls. Two of these controls contain just a series of ImageButtons. In the first of these controls the ImageButtons are generated in the page_load method and added to a panel using Panel.Controls.Add(ImageButtonCont...

adding row to a table control on button click
 Hi all, I'm trying to do something rather straightforward, but it's not working.I'm creating some sort of timesheet application where I want to be able to add rows with some date fields to my table control after I click on a button "add new row". This is the code I have behind the button "add row", and it works the first time I click it, but when I click it a second or a third time, no rows are being added... Any idea on how to solve this? Screenshot is here:  1 Protected Sub btnAddRow_Click(ByVal sender As Object, ByVal e As System.E...

Template column control not Visible in all Gridview rows
I got something odd here.  there is too much code to post, but I have a Template column in a GridView (created in design mode) with a RadioButtonList as the control in that column.  But RadioButtonList does NOT exist in all rows!!!  It shows in some rows.  I am not tinkering with the Visible property.  Oddly enough though, the rows it doesn't show in are the rows with partial data (some dataitems are emptystrings).  But that deosn't make any sense to me.  Anybody seen this before?    jP  I believe you need an e...

Adding a new row of controls on button click
Hi all,In a site I'm currently writing, I have a page in which users can add entries to the database.  The entries are very simple, consisting of selections from three drop down lists.In order to make it easier on the user, I would prefer to allow multiple entries to be created on the same page.  To keep the page clutter down, I want the user to be able to click on a button to add another row for entry creation on the same page.For a visual example of what I mean, check out this link. At the very bottom under "advanced search using boolean charts" is exactly what I wa...

Delete Control Button in Gridview Row at RowDataBound
I'd like to Delete a Control Button in a Gridview Row at RowDataBound, based on certain criteria.  I can locate the control during the event routine, but:Set = nothing gives "read only"Dispose =  has no effect Any suggestions on how I might be able to delete this button in this situation would be appreciated.Thanks!(PS:  one alt is to ADD the button in row created under the opposite criteria...I was hoping the get the above approach to work first, since it allows vanilla generation of the button.)  got it...in RowDatabound....If e.Row.RowType = D...

adding / deleting table rows, and accessing controls within added rows
Hi everyone,I would like to know what is a good and simple way to achieve this using asp.net.  Basically i would like the ability to add and delete rows, preferably table rows.  Against each row is its delete button, hitting it will delete the corresponding row.  There is only 1 Add button to add a new row.  In each row, there are say 2 textboxes.  When i hit, say a calculate button, i wish to be able to access all the available textboxes in all the available rows in the event handler, and say just output a sum.If GridView is suggested, could you please explain why i...

Gridview row click event fires, when clicking on controls within row.
I have a gridview control and I have added  a row click event which causes a post back. e.Row.Attributes.Add("onClick", this.Page.ClientScript.GetPostBackEventReference(this, "Select$" + e.Row.RowIndex.ToString()));  When the user clicks the row, i bind some data to a checkbox list, showing a uers a list of options they have chosen. All good so far. I also have a edit button for each row. When the row is in edit mode i display a checkbox and textbox. Problem is when i click on the textbox or the checkbox, it causes the row click event to fire. Any ida...

Adding data to gridview from two textboxes and then deleting them by delete button in each gridview row.
Hi, my app has 2 textboxes if i enter data and click add button they shud be added to gridview with 2 columns ex: custid from txtbox1 ... and custname frm txtbox2 added to gridview   with columns custid and custname then    foreach row a delete button shud appear in gridview and on clicking it shud delete the row can any one send me code for dis   thanks in advance Hi, In your Button Click Event write this code. DataControlField dCusId; DataControlField dCustName; dCusId.HeaderText = textbox1.text; dCustName.HeaderText = textbox2.text Gridv...

Urgent:How to Add Row with Control(RadioButton or CheckBox) to GridView in button Click
 Hi all,I have a DropDown in Page having values "Single" and "Multiple" .And one button outsidethe gridView.When i click on button should add one row to Gridview with RadioButton if DropDown selected is "Single"or CheckBox if  DropDown selected is "Multiple". How to Achieve this, help me urgent  Plz.From Ravi.    hiplease go here.Hope this wil help youhttp://www.codeproject.com/KB/miscctrl/Dynamic_Control.aspx  Warm Regards.Please don't forget to click "Mark as Answer" on the post that helped you....

Custom Gridview Control
I'm currently working on extending the functionality of the gridview control.  I've added a couple of features including a row click event, row hover style swapping, but now I'm curious if it's possible to add functionality similar to that of a button postbackurl property. With the button control, you can specify a postbackurl and the page will perform a cross page postback.  I'd like to add this functionality to my custom gridview control on row click, but I'm not sure where to start.  If I understand it right, I have to implement the IButtonControl in...

Web resources about - How to determine the row number when clicking a delete button I added to a template column from a GridView control??? - asp.net.presentation-controls

Control - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Obama may be able to do something on gun control at last: reports
US President Barack Obama is expected to announce executive actions expanding background checks on gun sales.

LG’s Amazon Echo-like device controls smart home devices and plays music
... a new device that looks somewhat familiar. The company announced its SmartThinq Hub today, a smart home hub with an LCD display that can control ...

Disable Windows 10 upgrade prompts with GWX Control Panel 1.7
... then the constant "Get Windows 10!" alerts are probably getting annoying. Fortunately you can disable them in seconds with the free GWX Control ...

Obama Meeting with Attorney General to Finalize Executive Gun Control
President Obama will meet with Attorney General Loretta Lynch to finalize the executive gun controls expected to be announced next week.

Thinga is a kid-friendly search engine with parental controls
Keeping kids away from questionable content while they surf the web is an ongoing battle, and there's a new site that's looking to help. Thinga, ...

The Air Traffic Control System Privatizing A Failed FAA NextGen Program Is Bad For America
For some reason, the sudden din from the aviation cognoscenti and aviation groupies to privatize the air traffic control system has gone way ...

NEW YEAR, NEW RULES Obama reportedly will use exec actions to tighten gun control
NEW YEAR, NEW RULES Obama reportedly will use exec actions to tighten gun control

PHOTOS: Hot To Trot Hunks Can Hardly Control Themselves In Brussels
PHOTOS: Hot To Trot Hunks Can Hardly Control Themselves In Brussels

Poland Lawmakers Approve New Law On State Media Control
WARSAW, Poland (AP) — Poland's parliament on Wednesday approved new legislation that gives the government control of state radio and television ...

Resources last updated: 1/2/2016 12:24:35 AM