Home > Software design >  DataGrid View Multicolored Cell Text
DataGrid View Multicolored Cell Text

Time:06-10

I was looking to see if it was possible to create multicolored cell text in an asp.net DataGrid View. The project that I'm working on contains a cell that has info related to the status of a unit which has the values of Unit1--DP, Unit2--ER, Unit3--ON and a couple others and I want to chance the color of each based on if it says AV, DP, ER, or ON. The ideal would be to color AV as Green, DP as Orange, ER as Yellow, and ON as Red.

Any information on how to do this would be helpful as there isn't much information as to if this is possible currently available.

CodePudding user response:

Ok, for a listview, Gridview, Repeater, and datalist?

The place for doing formating of the data (or grid) display is the DataBound event. (or ItemDataBound event).

This lets you see/grab/use/change/format the one row of data for each "repeated" item.

So, if I have a list of hotels, and say for a given city, I could color it blue like this:

    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) |
            (e.Item.ItemType == ListItemType.AlternatingItem)) {

            TextBox txtCity = e.Item.FindControl("City") as TextBox;
            if (txtCity.Text == "Edmonton")
            {
                // set background as blue
                txtCity.BackColor = System.Drawing.Color.LightSkyBlue;
            }
        }
    }

So, in your case, you could grab that control (find control), and then based on the text that follows the --, then you could color/set the background of that given control.

So, something close to this :

    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) |
            (e.Item.ItemType == ListItemType.AlternatingItem)) {

            TextBox txtCity = e.Item.FindControl("City") as TextBox;

            
            string[] strSufix = txtCity.Text.Split(new string[] { "--" },StringSplitOptions.None);

            if (strSufix[1] == "AV")
                txtCity.BackColor = System.Drawing.Color.LightGreen;

            if (strSufix[1] == "DP")
                txtCity.BackColor = System.Drawing.Color.Orange;

            if (strSufix[1] == "ER")
                txtCity.BackColor = System.Drawing.Color.Yellow;

            if (strSufix[1] == "ON")
                txtCity.BackColor = System.Drawing.Color.Red;

        }
    }

Edit: So user has gridview, and multiple items per cell.

So, say this markup:

        <asp:GridView ID="GridView1" runat="server" 
             AutoGenerateColumns="false" CssClass="table" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="FirstName"  HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName"   HeaderText="LastName"    />
                <asp:BoundField DataField="HotelName"  HeaderText="HotelName"  />
                <asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
                <asp:BoundField DataField="Test" HeaderText="Test" ItemStyle-Width="270" />
            </Columns>
        </asp:GridView>

Ok, and our code to load is this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadData();
    }

    void LoadData()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";

            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                DataTable rstData = new DataTable();
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());

                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

And now we get this:

enter image description here

so, as suggested, we add/use the Row data bound for such formatting.

So, we can use some code say like this:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // format 5th cell (cell 4)

            string celltext = e.Row.Cells[4].Text;
            string OcellText = celltext;  // save orginal fomat (with spaces)
            if (celltext.Contains("--"))
            {
                celltext = celltext.Replace(" ", ""); // trim blanks
                string[] Tokens = celltext.Split(',');
                foreach (string OneThing in Tokens)
                {
                    if (OneThing.Contains("--"))
                    {
                        string[] sufux = OneThing.Split(new string[] { "--" },StringSplitOptions.None);
                        if (sufux[1] == "AV")
                            OcellText = MyFormat(OcellText, OneThing, "LightGreen");

                        if (sufux[1] == "ON")
                            OcellText = MyFormat(OcellText, OneThing, "Red");
                    }
                }

                e.Row.Cells[4].Text = OcellText;
            }
        }
    }

    string MyFormat(string Source, string sFind, string MyColor)
    {

        string sHTML  = @"<span style=background-color:"   MyColor   ">"   sFind   "</span>";

        string MyResult = Source.Replace(sFind, sHTML);

        return MyResult;
    }

Now, when we run this, we get this:

enter image description here

  • Related