以编程方式选择 Asp.Net ListView 中的项目

发布于 2024-07-13 13:15:04 字数 1067 浏览 6 评论 0原文

经过快速搜索后,我找不到这个看似简单的事情的答案。

如何在 Asp.Net ListView 中手动选择项目?

我有一个 SelectedItemTemplate,但我不想使用 asp:button 或 asp:LinkBut​​ton 来选择项目。 我希望它可以从 URL 完成。 例如,像查询字符串一样。

我想象的方式是在 ItemDataBound 上,检查一个条件,然后将其设置为选中(如果为 true),但我该如何执行此操作?

例如:

protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e) {

  using (ListViewDataItem dataItem = (ListViewDataItem)e.Item) {

     if (dataItem != null) {
        if( /* item select condition */ ) {   

            // What do I do here to Set this Item to be Selected?
            // edit: Here's the solution I'm using :
            ((ListView)sender).SelectedIndex = dataItem.DisplayIndex;

            // Note, I get here and it gets set
            // but the SelectedItemTemplate isn't applied!!!

        }
     }
  }
}

我确定它只是一两行代码。

编辑:我已经更新了代码以反映解决方案,似乎我可以选择 ListView 的 SelectedItemIndex,但是,它实际上并未呈现 SelectedItemTemplate。 我不知道是否应该在 ItemDataBound 事件中执行此操作如下建议

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?

I have a SelectedItemTemplate, but I don't want to use an asp:button or asp:LinkButton to select an item. I want it to be done from a URL. Like a QueryString, for example.

The way I imagine would be on ItemDataBound, check a condition and then set it to selected if true, but how do I do this?

For example:

protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e) {

  using (ListViewDataItem dataItem = (ListViewDataItem)e.Item) {

     if (dataItem != null) {
        if( /* item select condition */ ) {   

            // What do I do here to Set this Item to be Selected?
            // edit: Here's the solution I'm using :
            ((ListView)sender).SelectedIndex = dataItem.DisplayIndex;

            // Note, I get here and it gets set
            // but the SelectedItemTemplate isn't applied!!!

        }
     }
  }
}

I'm sure it's one or two lines of code.

EDIT: I've updated the code to reflect the solution, and it seems that I can select the ListView's SelectedItemIndex, however, it's not actually rendering the SelectedItemTemplate. I don't know if I should be doing this in the ItemDataBound event as suggested below.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

恍梦境° 2024-07-20 13:15:04

我查看了 ListView 底层发生的一些事情,认为这可能是最好的方法。

void listView_ItemCreated(object sender, ListViewItemEventArgs e)
{
    // exit if we have already selected an item; This is mainly helpful for
    // postbacks, and will also serve to stop processing once we've found our
    // key; Optionally we could remove the ItemCreated event from the ListView 
    // here instead of just returning.
    if ( listView.SelectedIndex > -1 ) return; 

    ListViewDataItem item = e.Item as ListViewDataItem;
    // check to see if the item is the one we want to select (arbitrary) just return true if you want it selected
    if (DoSelectDataItem(item)==true)
    {
        // setting the SelectedIndex is all we really need to do unless 
        // we want to change the template the item will use to render;
        listView.SelectedIndex = item.DisplayIndex;
        if ( listView.SelectedItemTemplate != null )
        {
            // Unfortunately ListView has already a selected a template to use;
            // so clear that out
            e.Item.Controls.Clear();
            // intantiate the SelectedItemTemplate in our item;
            // ListView will DataBind it for us later after ItemCreated has finished!
            listView.SelectedItemTemplate.InstantiateIn(e.Item);
        }
    }
}

bool DoSelectDataItem(ListViewDataItem item)
{
    return item.DisplayIndex == 0; // selects the first item in the list (this is just an example after all; keeping it simple :D )
}

注释

  • ListView 选择项目在 DataBinding 事件触发后将使用的模板。 因此,如果在此之前设置了 SelectedIndex,则无需再进行任何工作。
  • 在 DataBinding 工作之后在任何地方设置 SelectedIndex,您只是得不到 SelectedItemTemplate。 为此,您要么重新绑定数据;要么 或重新实例化 ListViewItem 上的 SelectedItemTemplate。 一定要先清除 ListViewItem.Controls 集合!

更新 我已经删除了大部分原始解决方案,因为这应该可以更好地工作并适用于更多情况。

I looked at some of what's going on in ListView under the hood and think this is probably the best approach.

void listView_ItemCreated(object sender, ListViewItemEventArgs e)
{
    // exit if we have already selected an item; This is mainly helpful for
    // postbacks, and will also serve to stop processing once we've found our
    // key; Optionally we could remove the ItemCreated event from the ListView 
    // here instead of just returning.
    if ( listView.SelectedIndex > -1 ) return; 

    ListViewDataItem item = e.Item as ListViewDataItem;
    // check to see if the item is the one we want to select (arbitrary) just return true if you want it selected
    if (DoSelectDataItem(item)==true)
    {
        // setting the SelectedIndex is all we really need to do unless 
        // we want to change the template the item will use to render;
        listView.SelectedIndex = item.DisplayIndex;
        if ( listView.SelectedItemTemplate != null )
        {
            // Unfortunately ListView has already a selected a template to use;
            // so clear that out
            e.Item.Controls.Clear();
            // intantiate the SelectedItemTemplate in our item;
            // ListView will DataBind it for us later after ItemCreated has finished!
            listView.SelectedItemTemplate.InstantiateIn(e.Item);
        }
    }
}

bool DoSelectDataItem(ListViewDataItem item)
{
    return item.DisplayIndex == 0; // selects the first item in the list (this is just an example after all; keeping it simple :D )
}

NOTES

  • ListView selects the template an item will use after it's DataBinding event fires. So if the SelectedIndex is set before then, no more work is necessary
  • Setting the SelectedIndex anywhere after DataBinding works, you just don't get the SelectedItemTemplate. For that you have either rebind the data; or reinstantiate the SelectedItemTemplate on the ListViewItem. be sure to clear the ListViewItem.Controls collection first!

UPDATE I have removed most of my original solution, since this should work better and for more cases.

似最初 2024-07-20 13:15:04

您可以设置 ListViews SelectedIndex

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

更新

如果您在页面加载时加载数据,您可能必须遍历数据以查找索引,然后在调用 DataBind() 方法之前设置 SelectedIndex 值。

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<T>(this IEnumerable<T> source, Predicate<T> predicate)
    {
        int count = 0;
        foreach(var item in source)
        {
            if (predicate(item))
                return count;
            count++;
        }
        return -1;
    }
}

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<T>(this IEnumerable<T> source, Predicate<T> predicate)
    {
        int count = 0;
        foreach(var item in source)
        {
            if (predicate(item))
                return count;
            count++;
        }
        return -1;
    }
}
原野 2024-07-20 13:15:04
list.SelectedIndex = list.Items.IndexOf(item);
list.SelectedIndex = list.Items.IndexOf(item);
荒芜了季节 2024-07-20 13:15:04

扩展 @Jeremy 和 @bendewey 的答案,您不需要在 ItemDataBound 中执行此操作。 您只需要在设置 SelectedValue 之前已经进行 ListView 绑定即可。 您应该能够在 PreRender 期间执行此操作。 有关何时进行绑定的详细信息,请参阅此页面生命周期文档

Expanding on @Jeremy and @bendewey's answers, you shouldn't need to do this in ItemDataBound. You only need to have the ListView binding already have taken place before you set the SelectedValue. You should be able to do this during PreRender. See this page life cycle docs for more information on when binding takes place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文