Hi,
How you are using a gridview, to hide the ID, use the
DataKeyNames property of the component. You do not see the id.
<asp:GridView ID="grd_result" DataKeyNames="id" runat="server" OnRowCommand="grd_result_RowCommand">
To activate the button, do not use a button component in the TemplateField, use a
ButtonField component, it is easier. This button is executed by the
OnRowCommand event.
You can have many ButtonFields in your grid, to differentiate them use
CommandName property.
<asp:ButtonField ButtonType="Link" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px" CommandName="view" HeaderText="" Text="View" ControlStyle-BorderColor="Black" />
Here is an example to help you.
HTML CODE
<div>
<asp:GridView ID="grd_result" DataKeyNames="id" runat="server" EmptyDataText=":: No Data ::" AutoGenerateColumns="False" BorderStyle="Solid" OnRowCommand="grd_result_RowCommand" FooterStyle-CssClass="GridFooter" AllowPaging="false" ShowFooter="True">
<Columns>
<asp:ButtonField ButtonType="Link" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px" CommandName="view" HeaderText="" Text="View" ControlStyle-BorderColor="Black" />
<asp:BoundField HeaderText="Name" datafield="name" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
</div>
<br />
<asp:Label ID="lblmsg" runat="server" Text="-"></asp:Label>
CODE-BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");dt.Columns.Add("name");
DataRow dr = dt.NewRow();
dr["id"] = "1";dr["name"] = "John";dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = "2";dr["name"] = "Mary";dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = "3"; dr["name"] = "Sarah";dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = "4";dr["name"] = "Peter";dt.Rows.Add(dr);
this.grd_result.DataSource = dt;
this.grd_result.DataBind();
}
}
private bool user_permission(string user)
{
return true;
}
protected void grd_result_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (this.user_permission(this.Page.User.Identity.Name))
{
string current_command = e.CommandName;
int current_row_index = Int32.Parse(e.CommandArgument.ToString());
string id = this.grd_result.DataKeys[current_row_index].Value.ToString();
switch (current_command)
{
case "view":
{
this.lblmsg.Text = "My id is " + id + " and my name is " + this.grd_result.Rows[current_row_index].Cells[1].Text;
break;
}
}
}
else{this.lblmsg.Text = "You don't have permission to execute this task.";}
}
catch (Exception ex)
{
this.lblmsg.Text = "Error: " + ex.Message;
}
}