Objective: The objective is to set the System.Drawing.Color dynamically based on a text value within a datatable. The text value is the name of a color within System.Drawing.Color. The purpose is to change the backcolor of a grid based on the given value.
Issue: The method I am using now does not obtain a value from the datatable and sets the Color to 0,0,0,0. The datatable is created using a ViewState. The research I've conducted on this issue indicates this should work. However, the value obtained from the DataTable is "" . What is incorrect in this code? Thank you in advance for you comments, suggestions and consideration. The code is as follows:
DataTable code
private void CreateList()
{
DataTable dtMyList = new DataTable();
DataColumn dcID = new DataColumn("ID");
dtMyList.Columns.Add(dcID);
DataColumn dcColor = new DataColumn("Color");
dtMyList.Columns.Add(dcColor);
ViewState["MyList"] = dtMyList;
}
On RowDataBound code intended to change the backcolor
protected void grdMyList_RowDataBound(object sender, GridViewEventsArgs e)
{
DataTable dtMyList = (DataTable)ViewState["MyList"];
for (int i = 0; i < dtMyList.Rows.Count; i++)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.FromName(Convert.ToString(dtMyList.Rows[0]["Color"]));
}
}
First of all: Is the datatable filled with any data?
Second: you are trying to fill that one row (given in the event args) with all the colors from the datatable, resulting in that only one property (e.Row.Cells[0].BackColor
) is filled with the color coming from the last row in the table (dtMyList.Rows[i]["Color"]
).
I think you should first lookup the correct datarow which is attached to your gridrow (e.Row.DataItem
), then read its color and then fill the property of your gridrow. Like this:
protected void grdMyList_RowDataBound(object sender, GridViewEventsArgs e)
{
DataRow row = (DataRow)e.Row.DataItem;
e.Row.Cells[0].BackColor = System.Drawing.Color.FromName(row["Color"].ToString());
}