Hi ruben00000,
Please refer below sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<div style="width: 500px">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
</div>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" />
<script type="text/javascript">
$(function () {
$("[id*=gvCustomers]").DataTable({
bLengthChange: true,
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
bFilter: true,
bSort: true,
bPaginate: true
});
var selected = [];
$('[id*=gvCustomers] tbody').on('click', 'tr', function () {
var id = $(this).find('td').eq(0).html();
selected.push(id);
alert(JSON.stringify(selected));
});
});
</script>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerID, ContactName, City, Country FROM Customers", con))
{
con.Open();
gvCustomers.DataSource = cmd.ExecuteReader();
gvCustomers.DataBind();
con.Close();
//Required for jQuery DataTables to work.
gvCustomers.UseAccessibleHeader = true;
gvCustomers.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT CustomerID, ContactName, City, Country FROM Customers", con)
con.Open()
gvCustomers.DataSource = cmd.ExecuteReader()
gvCustomers.DataBind()
con.Close()
gvCustomers.UseAccessibleHeader = True
gvCustomers.HeaderRow.TableSection = TableRowSection.TableHeader
End Using
End Using
End If
End Sub
Screenshot