comunidadmexicana says:
gvProducts.DataKeyNames = "tkt";
You need to set string array to DataKeyNames.
So you need to convert the value to string array.
gvProducts.DataKeyNames = new string[] { "tkt"};
Refer below sample.
HTML
<asp:GridView runat="server" ID="gvCustomers"></asp:GridView>
<hr />
<asp:TextBox runat="server" ID="txtDataKey" /><br/><br/>
<asp:Button Text="Set Key Name" runat="server" OnClick="OnSet" />
<asp:Button Text="Get Key Name" runat="server" OnClick="OnGet" />
Namespace
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("CustomerId", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
protected void OnSet(object sender, EventArgs e)
{
gvCustomers.DataKeyNames = new string[] { txtDataKey.Text.Trim() };
BindGrid();
}
protected void OnGet(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Key Name : " + gvCustomers.DataKeyNames.GetValue(0) + "');", true);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {
New DataColumn("CustomerId", GetType(Integer)),
New DataColumn("Name", GetType(String)),
New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Sub
Protected Sub OnSet(ByVal sender As Object, ByVal e As EventArgs)
gvCustomers.DataKeyNames = New String() {txtDataKey.Text.Trim()}
BindGrid()
End Sub
Protected Sub OnGet(ByVal sender As Object, ByVal e As EventArgs)
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('Key Name : " & gvCustomers.DataKeyNames.GetValue(0) & "');", True)
End Sub
Screenshot