Show gridview rows in a different colour
iam displaying records in gridview,now my requirement is based on the transaction i want to show that rows in a different colour
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Nilanka DharmadasaRank #1,875 · 794 reputationPosted Nov 15, 2009, 6:36 PM EST
Use datagridview's CellPainting method to do that.
Let's say you want to check the value of 'Column2' and color your rows based on the value of that column.
So. you can write code as below.
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { try { if (e.RowIndex < 0) return; DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; if (row.Cells["Column1"].Value.ToString() == "abc") e.CellStyle.BackColor = Color.Red; } catch { } }If you find this answer useful, do not forgrt to mark this as accepted.
Lalit MRank #1,186 · 1.5K reputationPosted Nov 15, 2009, 6:40 PM EST
You can use and handle the RowDataBound event and then manipulate the DataRow. decimal priceTotal = 0; int quantityTotal = 0; void detailsGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // add the UnitPrice and QuantityTotal to the running total variables priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, _ "UnitPrice")); quantityTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _ "Quantity")); } else if (e.Row.RowType == DataControlRowType.Footer) { e.Row.Cells[0].Text = "Totals:"; // for the Footer, display the running totals e.Row.Cells[1].Text = priceTotal.ToString("c"); e.Row.Cells[2].Text = quantityTotal.ToString("d"); e.Row.Cells[1].HorizontalAlign = _ e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right; e.Row.Font.Bold = true; } }Lalit MRank #1,186 · 1.5K reputationPosted Nov 15, 2009, 6:52 PM EST