How to get read multiple more than one DataKeyNames from GridView RowCommand method in Asp.Net C# VB.Net

Using single DataKeyNames is easy for us. But in most complex cases we need to assign multiple or more than DataKeyNames values. Such as composite primary key. If we assign multiple or more than one DataKeyNames to a GridView by default we need to get or read multiple DataKeynames at a time to perform any action. This could be a Database modification or for business logic analysis. So here in this Asp.Net article i am going to explain how one can get or read multiple or more than one DataKeyNames from GridView RowCommand method in Asp.Net C# VB.Net.

Objective/Outcome:
get read multiple more than one DataKeyNames from GridView RowCommand method in Asp.Net C# VB.Net

To do the Example First Create 2 Database Tables:

CREATE TABLE [dbo].[Brand](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
 CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Product](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NULL,
	[Description] [varchar](max) NULL,
	[BrandID] [bigint] NULL,
 CONSTRAINT [PK_Product_2] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now Insert Some Data:

INSERT INTO Brand Values(1,'Kohinoor')
INSERT INTO Brand Values(2,'Proctor & Gamble')
INSERT INTO Brand Values(3,'Telenor')
INSERT INTO Brand Values(4,'Unilever')

INSERT INTO PRODUCT VALUES(1,'Lux Beauty Soap','Product of Unilever',4)
INSERT INTO PRODUCT VALUES(2,'Tibbet Pomed','Winter Product',1)
INSERT INTO PRODUCT VALUES(3,'Data SIM','Subscriber Identity Module',3)
INSERT INTO PRODUCT VALUES(4,'Nippon','Color Television',1)

Now modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Assign Multiple or More than One DataKeyNames in GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID,BrandID" OnRowCommand="GridView1_RowCommand" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" />
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Brand" HeaderText="Brand" />

                <asp:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" ></asp:LinkButton> 
                </ItemTemplate> 
                <EditItemTemplate> 
                </EditItemTemplate> 
                </asp:TemplateField>             

         </Columns>
        </asp:GridView>
       
       <hr />
        <asp:Label runat="server" ID="lblRowIndex" Font-Bold="True" Font-Size="Larger"></asp:Label>

Now Bind some Data to the GridView:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" +
                    " FROM Product P, Brand B" +
                    " WHERE P.BrandID=B.ID";

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                conn.Open();
                using (SqlDataAdapter da = new SqlDataAdapter(new SqlCommand(SQL, conn)))
                {
                    dt = new DataTable("tbl");
                    da.Fill(dt);
                }
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient”, “System.Configuration” namespaces.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dt As DataTable
            Dim SQL As [String] = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" & " FROM Product P, Brand B" & " WHERE P.BrandID=B.ID"

            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
                conn.Open()
                Using da As New SqlDataAdapter(New SqlCommand(SQL, conn))
                    dt = New DataTable("tbl")
                    da.Fill(dt)
                End Using
            End Using

            GridView1.DataSource = dt
            GridView1.DataBind()
        End If
    End Sub

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient”, “System.Configuration” namespaces.

Now Read Multiple or More Than One DataKeyNames from GridView:
C# Code:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Submit"))
        {
            GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int RowIndex = oItem.RowIndex;
            // If DataKeyNames contain single value
            //lblRowIndex.Text = GridView1.DataKeys[RowIndex].Value.ToString();

            // If DataKeyNames contain single value
            string SDataKeyNames = "";
            for (int i = 0; i < GridView1.DataKeyNames.Length; i++)
                SDataKeyNames += GridView1.DataKeyNames.GetValue(i).ToString() + ":" + GridView1.DataKeys[oItem.DataItemIndex][i].ToString() + ">>";
            lblRowIndex.Text = SDataKeyNames;
        }
    }

VB.Net Code:

    Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
        If e.CommandName.Equals("Submit") Then
            Dim oItem As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)
            Dim RowIndex As Integer = oItem.RowIndex
            ' If DataKeyNames contain single value
            'lblRowIndex.Text = GridView1.DataKeys[RowIndex].Value.ToString();

            ' If DataKeyNames contain single value
            Dim SDataKeyNames As String = ""
            For i As Integer = 0 To GridView1.DataKeyNames.Length - 1
                SDataKeyNames += GridView1.DataKeyNames.GetValue(i).ToString() & ":" & GridView1.DataKeys(oItem.DataItemIndex)(i).ToString() & ">>"
            Next
            lblRowIndex.Text = SDataKeyNames
        End If
    End Sub

Now run the project & click on the custom Link Button Action column to get more than one DataKeyNames.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Gridview, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

     

*