I have built the following custom control that I have built and I set the selected value when a bullet list item is clicked.
My problem is that I need to set the css class (SetSelected()) after postback, but it always picks up the previous entry in the viewstate rather than picking up the new value.
I don’t think I should be using PageLoad for setting the CSS class but am unsure where best to do this.
Can anyone help please?
[DefaultProperty("SelectedValue"),
ToolboxData("<{0}:GlossaryList runat=\"server\" />")]
public class GlossaryList : WebControl
{
const string MANAGEDMETADATASERVICE = "Managed Metadata Service";
const string TOYOTA = "Toyota";
BulletedList _bulletList = new BulletedList();
public String SelectedText
{
get
{
object selectedText = ViewState["SelectedText"];
return (selectedText == null) ? String.Empty : (string)selectedText;
}
set
{
ViewState["SelectedText"] = value;
}
}
public String SelectedValue
{
get
{
object selectedValue = ViewState["SelectedValue"];
return (selectedValue == null) ? String.Empty : (string)selectedValue;
}
set
{
ViewState["SelectedValue"] = value;
}
}
protected override void OnInit(EventArgs e)
{
CreateBulletedList();
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
if (this.Page.IsPostBack)
{
SetSelected();
}
base.OnLoad(e);
}
private void SetSelected()
{
//if(this.Controls != null && this.Controls.Count > 0)
//{
// foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
// {
// if (listItem.Value == SelectedValue)
// {
// listItem.Attributes.Add("class", "active");
// }
// }
//}
}
protected void CreateBulletedList()
{
_bulletList.Click += new BulletedListEventHandler(BulletListItem_Click);
_bulletList.DisplayMode = BulletedListDisplayMode.LinkButton;
_bulletList.CssClass = "letter-selector";
for (char c = 'A'; c <= 'Z'; c++)
{
ListItem listItem = new ListItem();
listItem.Text = c.ToString();
listItem.Value = c.ToString();
if (SelectedValue == c.ToString())
{
listItem.Attributes.Add("class", "active");
}
_bulletList.Items.Add(listItem);
}
if (!this.Page.IsPostBack)
{
_bulletList.Items[0].Selected = true;
_bulletList.Items[0].Attributes.Add("class", "active");
}
this.Controls.Add(_bulletList);
}
private void BulletListItem_Click(object sender, BulletedListEventArgs e)
{
SelectedValue = SelectedText = _bulletList.Items[e.Index].Value;
SetActive(e.Index);
}
private void SetActive(int index)
{
if (this.Controls != null && ((BulletedList)this.Controls[0]).Items.Count > 0)
{
foreach (ListItem listItem in ((BulletedList)this.Controls[0]).Items)
{
listItem.Attributes.Clear();
}
}
((BulletedList)this.Controls[0]).Items[index].Attributes.Add("class", "active");
}
}
Add following code:
Change the SetSelected method: