ASP Snippets

Categories




$4.95/month–Click Here!
ASP.NET Hosting,FREE SQL

Only $4.95/month – Click Here and Get a FREE SQL 2008 DB!



Alerts

Free Alerts

Your email will always be
private and will not be shared.




Follow us on twitter.




Zoom In | Zoom Out


Author is awarded Most Valuable Professional award by Microsoft ASP/ASP.Net

ASP.Net GridView - Get Row Index on RowCommand and Click events

Author:Mudassar Khan

Here I am explaining how to get the reference of the GridView Row and also the GridView Row Index when Button, ImageButton, or LinkButton is clicked or RowCommand Event is fired. In addition to that I will also explain how to add multiple CommandArguments to Control in GridView and retrieve the same.

 

 

Get GridView Row and GridView Row Index on RowCommand Event

 

Below is a simple ASP.Net GridView Control with a ButtonField and an OnRowCommand Event

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false" 

    OnRowCommand = "OnRowCommand">

 <Columns>

  <asp:ButtonField CommandName = "ButtonField"  DataTextField = "CustomerID"

        ButtonType = "Button"/>

 </Columns>

</asp:GridView>

 

Now when the Button of the button is clicked the OnRowCommand event is executed.

C#

protected void OnRowCommand(object sender, GridViewCommandEventArgs e)

{

    int index = Convert.ToInt32(e.CommandArgument);

    GridViewRow gvRow = GridView1.Rows[index]; 

}

 

VB.Net

Protected Sub OnRowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)

    Dim index As Integer = Convert.ToInt32(e.CommandArgument)

    Dim gvRow As GridViewRow = GridView1.Rows(index)

End Sub

 

The RowIndex of the GridView Row is contained in the CommandArgument Property. Thus with that index you can get the reference of the GridView Row.

 

 

 

Get GridView Row and GridView Row Index on Click Event of Button in TemplateField

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">

    <Columns>

        <asp:TemplateField>

        <ItemTemplate>

           <asp:Button ID="Button1" runat="server" Text='<%#Eval("CustomerID")%>'

                  CommandArgument = "Button1"  OnClick = "Button1_Click" />

        </ItemTemplate>

        </asp:TemplateField>

    </Columns>

</asp:GridView>

 

Now when the Button is clicked the Click event of the Button is executed.

C#

protected void Button1_Click(object sender, EventArgs e)

{

    GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;

    int index = gvRow.RowIndex;

}

 

VB.Net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)

    Dim gvRow As GridViewRow = CType(CType(sender, Control).Parent.Parent, _

                                        GridViewRow)

    Dim index As Integer = gvRow.RowIndex

End Sub

 

You will notice I am type casting the sender parameter to get the reference of the GridView Row. The sender is the Button Control, thus the parent of the Button Control is the Cell and the parent of the Cell is the GridView Row.

Button ----------> GridView Cell ----------> GridView Row

The same applies to LinkButton and ImageButton.

   

 

 

Get CommandArgument on Click Event of Button in TemplateField

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">

    <Columns>

        <asp:TemplateField>

        <ItemTemplate>

           <asp:Button ID="Button1" runat="server" Text='<%#Eval("CustomerID")%>'

                  CommandArgument = "Button1"  OnClick = "Button1_Click" />

        </ItemTemplate>

        </asp:TemplateField>

    </Columns>

</asp:GridView>

 

Many occasions you will need the properties of the Button like its CommandName, CommandArgument. So in that case you will need to get the reference of the Button using the sender parameter.

 

C#

protected void Button1_Click(object sender, EventArgs e)

{

    Button btn = (Button)sender;

    string CommandName = btn.CommandName;

    string CommandArgument = btn.CommandArgument;

}

 

VB.Net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)

   Dim btn As Button = CType(sender, Button)

   Dim CommandName As String = btn.CommandName

   Dim CommandArgument As String = btn.CommandArgument

End Sub

 

Same can be done with LinkButtons and ImageButtons by creating an object and assigning the sender after type casting 

   

 

 

Multiple values in CommandArgument

Now by default there’s no property to do it we need to use a simple string of concatenation and then splitting them into arrays Consider the following GridView

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">

    <Columns>

        <asp:TemplateField>

        <ItemTemplate>

         <asp:Button ID="Button1" runat="server" Text='<%#Eval("CustomerID")%>'

          CommandArgument=

          '<%#Eval("PostalCode") + "," + Eval("City") + "," + Eval("Country") %>' 

              OnClick = "Button1_Click" />

        </ItemTemplate>

        </asp:TemplateField>

    </Columns>

</asp:GridView>

 

Now to get these values you need to do the following

 

C#

protected void Button1_Click(object sender, EventArgs e)

{

    Button btn = (Button)sender;

    string[] CommandArgument = btn.CommandArgument.Split(',');

    string CommandArgument1 = CommandArgument[0];

    string CommandArgument2 = CommandArgument[1];

    string CommandArgument3 = CommandArgument[2];

}

 

VB.Net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)

   Dim btn As Button = CType(sender, Button)

   Dim CommandName As String = btn.CommandName

   Dim CommandArgument As String() = btn.CommandArgument.Split(",")

   Dim CommandArgument1 As String = CommandArgument(0)

   Dim CommandArgument2 As String = CommandArgument(1)

   Dim CommandArgument3 As String = CommandArgument(2)

End Sub

 

As you will notice I am simply splitting the values based on the separator I used to concatenate i.e. comma finally building a string array. Thus many times such basic concepts can make our job easier.

 

That’s it. This article comes to end. Hope you liked it.

Posted: Jun 27 2009, 04:20 by Mudassar Khan | Comments (10) RSS comment feed |
Filed under: ASP.Net | C# | GridView | VB.Net

Views: 13007
Page copy protected against web site content infringement by Copyscape


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share





Comments

Add comment


 

biuquote
  • Comment
  • Preview
Loading




0  +  0  =   










Community News





Web Hosting SpotLight


Consulting


For consulting and work related queries click here.



Advertise


Advertise with us. For more details click here.


Suggestions


Please provide your valuable suggesstions here.

This Site is hosted on

Lunarpages.com Web Hosting



Five New Videos on ASP.NET 4 and Visual Studio 2010!

Microsoft's Joe Stagner kicks off his series of ASP.NET 4 and Visual Studio 2010 "Quick Hits" videos. This series of short videos explains the new features of ASP.NET 4 and VS2010.


Updated Webcasts

Register for an upcoming webcast, or watch our expanded list of archived webcasts, to hear directly from the product team and industry experts on current and upcoming technologies.


Learn More about VS2010 and .NET 4 with Scott Guthrie's Continuing Blog Series

ScottGu continues his blog series on ASP.NET 4, covering WPF 4 and Add Reference Dialog Improvements.


New Video on Protecting Your ASP.NET Application from SQL Injection Vulnerabilities

Microsoft’s Joe Stagner explains how SQL Injection attacks can happen, what a bad guy can do with them, and how to protect your ASP.NET application from SQL Injection vulnerabilities.


Meet Scott Guthrie and the ASP.NET team at the ASP.NET Connections Conference in Las Vegas

Join us for a technical question and answer session with Scott Guthrie and members of the ASP.NET team on November 10th 2009 from 6:15 PM - 8:15PM at the ASP.NET Connections conference in Las Vegas. This is your chance to meet face to face with the people working on ASP.NET, give feedback and receive guidance. Attendance is limited so be there early and ask for details at the registration desk. We will have pizza and beverages.


The Minutes On 9 - Channel 9 Video Interviews with the ASP.NET 4 Team

Scott Hanselman conducts a series of interviews with developers and program managers on the ASP.NET 4 team. Get the inside scoop on Visual Studio 2010 and ASP.NET 4!


ASP.NET MVC Cheat Sheets

Microsoft MVP Elijah Manor shares lists of quick reference notes for working with ASP.NET MVC that he has collected across the web.


Learn About VS 2010's Coding Improvements with Scott Guthrie's Continuing Blog Series

ScottGu continues his blog series on ASP.NET 4, covering Searching and Navigating Code, and Intellisense Improvements


New Video on ASP.NET MVC

Chris Pels returns in a video that shows how to use the Json and JsonResult classes to return instances of classes as JSON formatted data. A sample MVC application is used to demonstrate the approach, and code downloads are available in both C# and VB.NET.


ASP.NET 4 Beta 2 and Visual Studio 2010 Beta 2 Released

Download ASP.NET 4 Beta 2 and Visual Studio 2010 Beta 2 which are now available with "go-live" licenses that allow you to use them on production machines. To learn more about the exciting new features and updates read the ASP.NET 4 and Visual Studio 2010 Web Development Overview whitepaper and the ASP.NET 4 Beta 2 breaking changes document. Ask questions and give feedback using the new ASP.NET 4 Beta 2 forum and the VS2010 Beta 2 forum.


New Additions to the ASP.NET Control Gallery!

Upload files, deliver reports with Silverlight, send email, and more with the latest additions to the ASP.NET Control Gallery!


URL Routing with ASP.NET 4 Web Forms

In the latest addition to Scott Guthrie's blog series on the upcoming VS 2010 and .NET 4 release, learn about ASP.NET 4's new cool runtime feature that allows you to use URL routing with Web Forms based pages.


Microsoft Ajax Library Preview 6

This latest preview release contains exciting new features like script loader, jQuery integration and the Microsoft Ajax Minifier tool. Script loader automatically and efficiently loads the scripts required by your application. jQuery integration allows you to seamlessly use both jQuery plug-ins and Microsoft Ajax controls within the same application. The Microsoft Ajax Minifier tool helps reduce the size of script files by utilizing a variety of minification techniques. Download Microsoft Ajax Library Preview 6 or use it directly from our Microsoft Ajax Content Delivery Network.


New Podcasts!

Listen to popular community members discuss and debate issues of interest to all ASP.NET developers in the newest series of podcasts. Scott Hanselman, .NET Rocks!, and others have checked in with new episodes.


Two New Videos from Joe Stagner!

In the first of this week's new videos, Microsoft's Joe Stagner shows how ASP.NET helps you understand and easily defend against Cross Site Scripting (XSS) in your Web Applications. And in the second video, Joe introduces programming with LINQ and compares simple data access between ADO.NET and LINQ from a developer experience perspective.