Hi kankon,
Refer below code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<form id="form1" runat="server">
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
Font-Names="Arial" Font-Size="10" RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White"
AlternatingRowStyle-ForeColor="#000" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="txtName" Text='<%# Eval("ContactName") %>' runat="server" Width="120" />
<asp:Button ID="btnShow" runat="server" Text="Show Text" Width="120" OnClick="btnShow_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
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)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 ContactName FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void btnShow_Click(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
string name = (row.FindControl("txtName") as Label).Text.Trim();
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + name + "')", true);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 ContactName FROM Customers")
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub btnShow_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim row As GridViewRow = TryCast((TryCast(sender, Button)).NamingContainer, GridViewRow)
Dim name As String = TryCast(row.FindControl("txtName"), Label).Text.Trim()
ClientScript.RegisterClientScriptBlock(Me.GetType(), "", "alert('" & name & "')", True)
End Sub
Screenshot