hi kankon,
Please refer below code.
HTML
<asp:GridView runat="server" ID="gvEmployees" AutoGenerateColumns="false" DataKeyNames="EmployeeId,CountryId"
OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="Employee ID" DataField="EmployeeId" />
<asp:BoundField HeaderText="Employee Name" DataField="EmployeeName" />
<asp:TemplateField HeaderText="Cancel request">
<ItemTemplate>
<asp:Button ID="btnNewRequest1" runat="server" Text="Cancel request" OnClick="Oncancel" ></asp:Button>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowDeleteButton="true" HeaderText="حذف"
ControlStyle-Width="50" HeaderStyle-HorizontalAlign="Center" HeaderStyle-Width="50">
<ControlStyle Width="50px"></ControlStyle>
<HeaderStyle HorizontalAlign="Center" Width="50px"></HeaderStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
Namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmployeeId, EmployeeName, CountryId FROM Employees", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvEmployees.DataSource = dt;
gvEmployees.DataBind();
}
}
}
}
}
protected void Oncancel(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE EMPLOYEES SET CountryId= @CountryId WHERE EmployeeId=@id", con))
{
string id = gvEmployees.DataKeys[row.RowIndex].Values[0].ToString();
cmd.Parameters.AddWithValue("@CountryId", "Cancelled");
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (gvEmployees.DataKeys[e.Row.RowIndex].Values[1].ToString() == "Cancelled")
{
e.Row.BackColor = Color.Red;
}
}
}
Screenshot