Introduction
In this article i will explain about how to change the Grid row color dynamically based on condition.
Practice
For performing Grid operation you can directly drag and drop grid control from Toolbox and do code according your need or for better understanding you can copy the code which i am sharing below.
Design View ___
<asp:GridView ID="gvEmployeeInfo" runat="server" AutoGenerateColumns="false"
AllowPaging="true" OnRowDataBound="gvEmployeeInfo_RowDataBound">
<Columns>
<asp:BoundField DataField="EmpId" HeaderText="Employee Id" />
<asp:BoundField DataField="Name" HeaderText="Employee Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
</Columns>
</asp:GridView>
|
In above Grid Code I used OnRowDataBound Event to handle dynamic change on Grid Row. RowDataBound Event is fire while DataSource assigning to Grid and when the GridView row selection change performs during the postback
Code View ___
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Employee;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
gvEmployeeInfo.DataSource = ds;
gvEmployeeInfo.DataBind();
}
protected void gvEmployeeInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Convert.ToInt32(e.Row.Cells[2].Text) > 15000)
{
e.Row.BackColor = Color.AliceBlue;
}
else if (Convert.ToInt32(e.Row.Cells[2].Text) < 50000)
{
e.Row.BackColor = Color.Red;
}
else
{
e.Row.BackColor = Color.LightGray;
}
}
}
|
In the above code i directly fetch the data from database using simple sql query but it is not a good way to perform big operation.
0 comments:
Post a Comment