Hi mahjoubi,
Declare a HiddenField and set its value in client side. So that you can access in code behind.
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Get Header Text" runat="server" OnClick="OnGet" />
<input type="hidden" id="HeadertTxt" name="HeadertTxt" value="" />
<script type="text/javascript">
function GetHeaderText(txt) {
document.getElementById("HeadertTxt").value = txt;
}
</script>
Namespaces
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{
new DataColumn("Id"),
new DataColumn("Name"),
new DataColumn("Country")
});
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");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (DataControlFieldCell cell in e.Row.Cells)
{
cell.Attributes.Add("onclick", "javascript: GetHeaderText('" + cell.Text + "')");
}
}
}
protected void OnGet(object sender, EventArgs e)
{
string headerText = Request.Form["HeadertTxt"];
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + headerText + "')", true);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {
New DataColumn("Id"),
New DataColumn("Name"),
New DataColumn("Country")})
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")
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Header Then
For Each cell As DataControlFieldCell In e.Row.Cells
cell.Attributes.Add("onclick", "javascript: GetHeaderText('" & cell.Text & "')")
Next
End If
End Sub
Protected Sub OnGet(ByVal sender As Object, ByVal e As EventArgs)
Dim headerText As String = Request.Form("HeadertTxt")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "", "alert('" & headerText & "')", True)
End Sub
Screenshot