I need to change the background colour of specific list items in a dynamically bound drop down list. The specific items which need to be highlighted are also dynamic and stored in a dataset. This way the user knows the item has already been selected elsewhere in the program, but still has the choice to select it if they wish.
Below is my code:
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
string strWeek = ((Label)e.Row.FindControl("lblWeek")).Text.ToString();
string strBed = ((Label)e.Row.FindControl("lblBed")).Text.ToString();
string strJob = getSelectedJob(strBed, strWeek);
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#f8f8ff");
DataTable myTable = new DataTable();
DataColumn EIDColumn = new DataColumn("EID");
DataColumn EventNameColumn = new DataColumn("EventName");
myTable.Columns.Add(EIDColumn);
myTable.Columns.Add(EventNameColumn);
DataSet ds = new DataSet();
ds = getJobs(strBed, strWeek, ddlTerm.SelectedValue.ToString(), strJob);
DataSet ds2 = new DataSet();
ds2 = getAssignedJobs(strBed);
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlEssential");
DataRow[] rows = ds.Tables[0].Select();
foreach (DataRow row in rows)
{
DataRow newRow = myTable.NewRow();
newRow["EID"] = row["EID"];
newRow["EventName"] = row["EventName"];
myTable.Rows.Add(newRow);
}
ddl.DataSource = myTable;
ddl.DataTextField = "EventName";
ddl.DataValueField = "EID";
ddl.DataBind();
ddl.Items.FindByValue(strJob).Selected = true;
foreach (DataRow row in ds2.Tables[0].Select())
{
string strAssignedJob = row["EID"].ToString();
ddl.Items.FindByValue(strAssignedJob).Attributes.Add("style", "background-color:#cccccc");
}
}
I’m getting this error Object reference not set to an instance of an object. and it seems to be occuring on the line that adds the style attribute to the drop down list.
Is this even possible or is my loop statement incorrect?
Thanks so much!
Thanks Tariqulazam. You pointed me in the right direction.
I’ve since modified the structure of my code and it’s giving me exactly what I want. By assigning the value of the ‘FindByValue’ to a variable, I was able to better test if it was null.