且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从数据库中突出显示列表框中已选择的项目

更新时间:2023-11-28 20:36:10

使用事件数据绑定事件 [
Use event DataBound Event[^]

OnDataBound event, check if the value was earlier selected - if so, apply different style to that listitem. Define a Databound handler for the ListBox. During databind, the execution will go through this method then.

Something like:
protected void lstMultipleValues_DataBound(object sender, EventArgs e)
{
  foreach (ListItem item in lstMultipleValues.Items)
  {
    //check anything out here
    if (item.Text.StartsWith("B"))
      item.Attributes.Add("style", "color:red");
  }
}


如果您尝试手动执行此操作,并且没有数据绑定,则如下所示:

If you''re trying to manually do it, and are not databound, something like this:

<asp:listbox id="list1" runat="server" selectionmode="Multiple" xmlns:asp="#unknown">
    <asp:listitem value="1" text="Apple"></asp:listitem>
    <asp:listitem value="2" text="Orange"></asp:listitem>
    <asp:listitem value="3" text="Banana"></asp:listitem>
    <asp:listitem value="4" text="Pear"></asp:listitem>
</asp:listbox>



背后的代码:



Codebehind:

// Selections coming from your database
string selections = "2,4";  

// Create array of selected values
string[] selectedValues = selections.Split('','');

// Make sure there can be multiple value selected on you list box
list1.SelectionMode = ListSelectionMode.Multiple;

foreach (string value in selectedValues)
{
    ListItem item = list1.Items.FindByValue(value);
    if (item != null)
    {
	item.Selected = true;
    }
}