I want to change the color of some special words NOT all words in a gridview cell.
Here is the code:
protected void gvContents_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[3].Text.Contains("Special"))
{
//set The "Special" word only forecolor to red
}
else if (e.Row.Cells[3].Text == "Perishable")
{
//set The "Perishable" word only forecolor to blue
}
else if (e.Row.Cells[3].Text == "Danger")
{
//set The "Danger" word only forecolor to yellow
}
}
}
and the cell text might be like here: Radioactive : Danger or this: Human Body : Special ,Perishable. What should I do?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use a combination of span tags and CSS classes. First create the CSS classes in your aspx code:
<style>
.redWord
{
color: Red;
}
.blueWord
{
color: Blue;
}
.yellowWord
{
color: Yellow;
}
</style>
then replace all occurences of Special to <span class='redWord'>Special</span>, Perishable to <span class='blueWord'>Perishable</span>, and Danger to <span class='yellowWord'>Danger</span>:
protected void gvContents_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[3].Text = e.Row.Cells[3].Text.Replace("Special", "<span class='redWord'>Special</span>")
.Replace("Perishable", "<span class='blueWord'>Perishable</span>")
.Replace("Danger", "<span class='yellowWord'>Danger</span>");
}
}
Method 2
In the CellFormatting event handler, add the below code
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.Value != null && e.Value.ToString() == "Special")
{
e.CellStyle.ForeColor = Color.Red;
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0