Programmatically Select Item in Asp.Net ListView

后端 未结 4 1235
悲哀的现实
悲哀的现实 2020-12-05 08:48

After doing a quick search I can\'t find the answer to this seemingly simple thing to do.

How do I Manually Select An Item in an Asp.Net ListView? <

4条回答
  •  无人及你
    2020-12-05 09:46

    You can set the ListViews SelectedIndex

    list.SelectedIndex = dataItem.DisplayIndex; // don't know which index you need
    list.SelectedIndex = dataItem.DataItemIndex; 
    

    Update

    If your loading the data on page load you may have to traverse the data to find the index then set the SelectedIndex value before calling the DataBind() method.

    public void Page_Load(object sender, EventArgs e)
    {
      var myData = MyDataSource.GetPeople();
      list.DataSource = myData;
      list.SelectedIndex = myData.FirstIndexOf(p => p.Name.Equals("Bob", StringComparison.InvariantCultureIgnoreCase));
      list.DataBind();
    }
    
    
    public static class EnumerableExtensions
    {
        public static int FirstIndexOf(this IEnumerable source, Predicate predicate)
        {
            int count = 0;
            foreach(var item in source)
            {
                if (predicate(item))
                    return count;
                count++;
            }
            return -1;
        }
    }
    

提交回复
热议问题