Wednesday, September 17, 2008

ASP.NET Dynamic Data Color Selector.

Well my problem was that I had a table in which I needed to be able to pick up colors.

so here's the small tutorial

1. Create a user control called ColorPicker and other ColorPicker_edit

2. The colorpicker, will show the color in the background of a disabled textbox.

This is really easy

<asp:TextBox Id="TextBox1" runat="server" Enabled="false" BorderWidth="0" BackColor="<%# System.Drawing.Color.FromName(FieldValueString) %>" ></asp:TextBox>


3. In the ColorPicker_edit we will have the following methods.

Basically its a dropdownlist and each item has as its background the color.

Method 1:
BindFillColorList: It fills the dropdownlist with all the known colors.

private void SetCbackColorsForListItems()
  {
      foreach (ListItem li in DropDownList1.Items)
      {
          li.Attributes["style"] = " background-color: " + li.Value;
      }
  }



Method 2. In the Page_load, we will fill this list, but we also need to put as backcolor, the name of the color.

protected void Page_Load(object sender, System.EventArgs e)
{
//if (!IsPostBack)
BindFillColorslist();
//set the Background color of the listitem to the same color which the item represents
SetCbackColorsForListItems();
}
private void SetCbackColorsForListItems()
{
foreach (ListItem li in DropDownList1.Items)
{
li.Attributes["style"] = " background-color: " + li.Value;
}
}

3. We need a way to find the selected color, thats done with the SelectedColor Property

public System.Drawing.Color SelectedColor
{
get
{
if (DropDownList1.SelectedIndex > 0)
{
//get the selected color
string SelectedColorStr = DropDownList1.SelectedValue;
//' conver the color string to System.drawing.color object
System.Drawing.ColorConverter converter = new System.Drawing.ColorConverter();
System.Drawing.Color objColor =
(System.Drawing.Color)converter.ConvertFromString(SelectedColorStr);
return objColor;
}
// if there is no color selected
// we return empty color object
else
{
return new System.Drawing.Color();
}
}
set
{
string Color = value.Name;
ListItem li = DropDownList1.Items.FindByValue(Color);
// if found in the colors list , we select the matched color
if (li != null)
{
DropDownList1.ClearSelection();
li.Selected = true;
}
}

}

4. And finally, we need that in Edit mode in the detailsview the dropdown is selected in the appropiate color.


As simple as this:
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
if (Mode == DataBoundControlMode.Edit)
{
ListItem item = DropDownList1.Items.FindByValue(FieldValueString);
if (item != null)
{
// if we get the value set the drop down list to FieldValueString
DropDownList1.SelectedValue = FieldValueString;
}
}
}

Then in your Sql to Entitie class you only need to add the UIHint and it will work right away.

[UIHint("ColorPicker")]
public object color { get; set; }


Thanks!

No comments: