Hi Lingers,
Please refer below sample.
HTML
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvDetails_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Town" HeaderText="Town" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="lnkView" runat="server" Text="View" OnClick="View" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespace
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Session["privilege"] = 2;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Age"), new DataColumn("Town") });
dt.Rows.Add(1, "Ares", 25, "Los Angeles");
dt.Rows.Add(2, "Demon", 22, "New York");
dt.Rows.Add(3, "Elena", 20, "Mystic Falls");
dt.Rows.Add(4, "Rohan", 30, "Mumbai");
dt.Rows.Add(5, "Amit", 18, "Las Vegas");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
}
protected void View(object sender, EventArgs e)
{
}
protected void Edit(object sender, EventArgs e)
{
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button lnkView = (e.Row.FindControl("lnkView") as Button);
if (Convert.ToInt32(Session["privilege"]) == 2)
{
lnkView.Enabled = false;
}
else
{
lnkView.Enabled = true;
}
}
}
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Session("privilege") = 2
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(3) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Age"), New DataColumn("Town")})
dt.Rows.Add(1, "Ares", 25, "Los Angeles")
dt.Rows.Add(2, "Demon", 22, "New York")
dt.Rows.Add(3, "Elena", 20, "Mystic Falls")
dt.Rows.Add(4, "Rohan", 30, "Mumbai")
dt.Rows.Add(5, "Amit", 18, "Las Vegas")
gvDetails.DataSource = dt
gvDetails.DataBind()
End If
End Sub
Protected Sub View(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Edit(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub gvDetails_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lnkView As Button = (TryCast(e.Row.FindControl("lnkView"), Button))
If Convert.ToInt32(Session("privilege")) = 2 Then
lnkView.Enabled = False
Else
lnkView.Enabled = True
End If
End If
End Sub
Screenshot