天道酬勤,学无止境

ObjectListView cast exception (for hit testing)

I am using Grammarian's ObjectListView. I changed my old listviews to that, but all I do is to fill in items. But when the app starts up and my mouse is over the listview, it immediately throws an exception for:

System.InvalidCastException was unhandled
  Message="Unable to cast object of type 'System.Windows.Forms.ListViewItem' to type 'BrightIdeasSoftware.OLVListItem'."
  Source="ObjectListView"

How to fix this?

Also I use Win7 if that's important.

EDIT:

I use a dictionary. It looks like I need to use the SetObjects method instead of adding items.

Ok this is great, but I am just using the dict.Value collection. I don't want to modify the data through listview, only show. So I have only 1 column and list everything there which are strings. Is this possible?

I would appreciate a small sample.

评论

You are right -- you should be using the SetObjects() method rather than adding ListViewItems. In an ObjectListView, there should never be ListViewItems. The control keeps track of more information and so needs more than ListViewItems provides.

You might want to read the Getting Started page of the website, especially the Unlearn you must section.

ObjectListView does have its own forum, if you want to ask questions there.

Answer for OP:

As far as I understand, you are using a dictionary where the value type is a string.

This shows me a list of the values in the dictionary, in Details mode.

        // Create dictionary.. Can be done somewhere else..
        var dictionary = new Dictionary<int, string>();
        dictionary.Add(1, "Item 1");
        dictionary.Add(2, "Item 2");

        // You can set up the column in the designer as well.
        objectListView1.Columns.Add(new OLVColumn(title: "Items", aspect: "Value"));
        // Initially tells OLV to use the dictionary as a datasource.
        objectListView1.SetObjects(dictionary);

        // .....


        // Later on, you can add another item to the dictionary.
        dictionary.Add(3, "Item 3");
        // All you have to do now, is call .BuildList(), and your listview is updated.
        // shouldPreserveState can be false if you want. I want it to be true. :)
        objectListView1.BuildList(shouldPreserveState:true);

This is not exactly "one line", but if you do set up the column in the designer, then SetObjects() is really that one line to activate it. You just have to remember to call BuildList whenever your dictionary changes.


Answer for @ElektroStudios

Okay, so for some reason you want to use ListViewItem as your "data container". This is not the intended usage for OLV, as pointed out by @Grammarian, but as ListViewItem is a class with properties as any other class with properties, this is easily done.

This is not a "one-liner", but it most definitely isn't a write a 1000 lines model class... Just to add 1 string to a ListView. Note I specified 2 ways of setting up the getters for the columns.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Items collection.
        // Add your list view items to this.
        // Note the fact that we have a different amount of subitems!!!
        var items = new List<ListViewItem>
        {
            new ListViewItem(new []{"Hello", "Stack","Overflow"}), 
            new ListViewItem(new []{"ObjectListView is pretty damn neat!"}), 
            new ListViewItem(new []{"Pretty", "Cool"})
        };

        // These are set up by the WinForms Designer when I create OLV columns in the designer.

        // Here, I am telling each column to use a custom getter, created by the SubItemGetter method.
        // ensures the sub-items actually exist on each LVI.
        olvColumn1.AspectGetter = SubItemGetter(0); // ListViewItem's first sub-item is the same as ListViewItem.Text. :)
        olvColumn2.AspectGetter = SubItemGetter(1);
        olvColumn3.AspectGetter = SubItemGetter(2);

        // NOTE: I assume you know at design-time how many columns there are in your list view.
        // Set them up as I've done above, or, if you want to be fancy..
        for (int index = 0; index < objectListView1.Columns.Count; index++)
        {
            OLVColumn column = objectListView1.AllColumns[index];
            column.AspectGetter = SubItemGetter(index);
        }

        // Tells OLV to use the items collection.
        objectListView1.SetObjects(items);

        // Sometime later, probably somewhere else in the code...
        items.Add(new ListViewItem(new []{"I","Dont","Care","How","Many","SubItems","There","Is!"}));
        // Tell OLV to rebuild!
        objectListView1.BuildList(shouldPreserveState:true); // I'd like to preserve state, please :)
    }

    private AspectGetterDelegate SubItemGetter(int subItemIndex)
    {
        // This returns a method that gives OLV the string it needs to render each cell,
        // while also making sure the sub item exists.
        return rowObject =>
        {
            // Cast the row object to a ListViewItem. This should be safe.
            var lvi = (ListViewItem) rowObject;
            // Make sure the index is not out of range.
            if (lvi.SubItems.Count <= subItemIndex)
                return null;
            // Return what needs to be displayed!
            return lvi.SubItems[subItemIndex].Text;
        };
    }
}

This gives me a default looking OLV like this (note the grouping is configurable!)..

Form..

In regards to Grammarian's answer, what they do not tell you is this.

They tell you that you need just one line to activate it, but you will find it's a headache and a lot more work then it's worth. I highly suggest you to stick to the normal ListView, otherwise you will find yourself writing a 1000 lines model class... Just to add 1 string to a ListView.

Just the truth about this ObjectListView business before you look too much into it...

Go download the example and take a look, I find it easier to just use a normal ListView frankly.

I got a similar error when trying to pass a normal ListView in virtual mode to ListViewPrinter in OLV 2.7

The error occurred here:
#if !WITHOUT_OBJECTLISTVIEW
        /// <summary>
        /// Get the nth item from the given listview, which is in virtual mode.
        /// </summary>
        /// <param name="lv">The ListView in virtual mode</param>
        /// <param name="n">index of item to get</param>
        /// <returns>the item</returns>
        override protected ListViewItem GetVirtualItem(ListView lv, int n)
        {
// Invalid Cast happens here
            return ((VirtualObjectListView)lv).MakeListViewItem(n);
        }

It works as expected with an objectlistview. No solution except to use an objectlistview.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
    I have 2 tables in SQL. One is called Training and one is called Consultants. Training is couple of fields like ID, Place, Time, Date and it also has ConsultantName which is foreign key and is connected with Consultants having ConsultantName, ConsultantFirstName etc. During save of Training i save the training first and then pass the Training value as varTraining. I tried to attatch it to context as per some suggestions I found on stack but it doesn't seem to work: Training Training = context.Trainings.First(p => p.TrainingID == varTraining.TrainingID); context.Trainings.Attach(Training)
  • ObjectListView show icons
    Trying to put icons in ObjectListview, here's my piece of code where icon should have been put: objectListView1.SmallImageList = imageList1; deleteColumn.IsEditable = true; deleteColumn.ImageGetter = delegate { return 0; }; deleteColumn.AspectGetter = delegate { return "Delete"; }; imageList1 already have an image, this code should have put an icon next to "Delete", but it did not appear at all, looked through cookbooks and Google and I still have no idea. Can anyone help me? this is the full form code in case needed: using System; using System.Collections.Generic; using System.ComponentModel
  • How to add a new item into ObjectListView?
    I tried the demo code in demo project but I can't add new item successfully. It just add new new NULL group and NULL item. Please give me an simple example code to add new item (text and image). Thank you! Oh sorry! I forgot it. This is the first time I participate in this site. I use C#. And the code is: objectListView1.BeginUpdate(); objectListView1.AddObject(new string [] {"Hello","dfdsF" }); objectListView1.EndUpdate(); and objectListView1.BeginUpdate(); OLVListItem item = new OLVListItem(new string [] {"Hello","dfdsF" }); objectListView1.Items.Add(item); objectListView1.EndUpdate(); It's
  • Performance hit from C++ style casts?
    I am new to C++ style casts and I am worried that using C++ style casts will ruin the performance of my application because I have a real-time-critical deadline in my interrupt-service-routine. I heard that some casts will even throw exceptions! I would like to use the C++ style casts because it would make my code more "robust". However, if there is any performance hit then I will probably not use C++ style casts and will instead spend more time testing the code that uses C-style casts. Has anyone done any rigorous testing/profiling to compare the performance of C++ style casts to C style
  • How to wordWrap the text in a column using ObjectListView
    For example I have a big sentence: "I like to eat pie and have fun around the house all day long!" And I want it to appear like this: "I like to eat pie and have fun around the house all day long!" In this post: Multi-line list items on WinForms ListView control? Grammarian said that you only need to have WordWrap on but I cannot find that option. Thanks for the help in advanced
  • Objectlistview how to change the text in the group header?
    I want to change the name of the group header but i cant find any solutions in the documentation or on google. the text in the header should be a time which is summed up in the group. this is how it should look like:
  • 展平Google Analytics(分析)数据(具有重复的字段)不再起作用(Flattening Google Analytics data (with repeated fields) not working anymore)
    问题 我们拥有一个高级Google Analytics(分析)帐户,该帐户可让我们访问行级事件数据。 该数据每天导出到Google Bigquery,并且每天都会在数据集中创建一个新表。 直到一周前,我们可以将Google Analytics(分析)数据展平到临时登台表,然后将其导出为CSV,从而将其导出为CSV。 我们过去这样做的查询是这样的: SELECT * FROM flatten([xxxxxxxx.ga_sessions_20140829],hits), flatten([xxxxxxxx.ga_sessions_20140828],hits), flatten([xxxxxxxx.ga_sessions_20140827],hits), flatten([xxxxxxxx.ga_sessions_20140826],hits) 昨天我注意到此查询现在将引发错误: Cannot output multiple independently repeated fields at the same time. Found customDimensions_value and hits_product_productSKU 显然,关于flatten()函数已经有所更改,因为hits_product_productSKU是hits字段的子代。
  • 即使将焦点放在另一个控件上,如何更改listview所选行的背景色?(How to change listview selected row backcolor even when focus on another control?)
    问题 我有一个使用条形码扫描仪作为输入设备的程序,这意味着我需要将重点放在文本框上。 该程序具有一个listview控件,当扫描特定条形码时,我将以编程方式选择其中一项。 我通过以下方式设置行的背景色: listviewitem.BackColor = Color.LightSteelBlue; 我尝试过的事情: listview.HideSelection设置为false 设置颜色后调用listview.Focus() listviewitem.Focused设置为true 呼叫listview.Invalidate 呼叫listview.Update() 调用listview.Refresh() 上面的不同组合 我还在计时器中进行了上述组合,因此它们在不同的线程上被调用,但仍然没有成功。 有任何想法吗? 更多信息: 这里的关键是控制焦点。 选择其中一项时, listview控件没有焦点。 我通过执行以下操作选择一项: listView1.Items[index].Selected = true; 焦点始终在文本框中。 该计算机没有键盘或鼠标,只有条形码读取器。 我有以下代码可以将重点放在文本框上: private void txtBarcode_Leave(object sender, EventArgs e) { this.txtBarcode.Focus(); }
  • 如何将字符串转换为整数,并在PostgreSQL转换时出现错误的情况下将其设置为0?(How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?)
    问题 在PostgreSQL中,我有一个带有varchar列的表。 数据应该是整数,我需要在查询中使用整数类型。 一些值是空字符串。 以下: SELECT myfield::integer FROM mytable 产生ERROR: invalid input syntax for integer: "" 如何在postgres中进行强制转换时查询强制转换,并在错误的情况下将其设置为0? 回答1 我本人只是在为类似的问题而苦苦挣扎,但又不想增加函数的开销。 我想出了以下查询: SELECT myfield::integer FROM mytable WHERE myfield ~ E'^\\d+$'; Postgres缩短了它的条件条件,因此您不应让:: integer演员遇到任何非整数。 它还处理NULL值(它们与regexp不匹配)。 如果您希望零而不是不选择,那么CASE语句应该起作用: SELECT CASE WHEN myfield~E'^\\d+$' THEN myfield::integer ELSE 0 END FROM mytable; 回答2 您还可以创建自己的转换函数,在其中可以使用异常块: CREATE OR REPLACE FUNCTION convert_to_integer(v_input text) RETURNS INTEGER AS $$
  • 按列对ListView排序(Sorting A ListView By Column)
    问题 当前,我在列表视图上使用自定义排序器,并且每次单击FIRST列时都可以对列表视图进行排序,但是不会按其他列进行排序。 SortStyle:用于确定是升序还是降序的变量。 if (e.Column == 0) { if (SortStyle == 0) { List.ListViewItemSorter = customSortDsc; SortStyle = 1; } else { List.ListViewItemSorter = customSortAsc; SortStyle = 0; } } 在对第一列进行排序时,这可以很好地工作,但是如果要在其他任何列上进行排序,则只会按第一列进行排序。 有没有一种方法可以对单击的列进行排序? 回答1 如果您从ListView开始,请帮自己一个忙,使用ObjectListView代替。 ObjectListView是.NET WinForms ListView的开源包装,它使ListView更加易于使用,并为您解决了许多常见问题。 按列单击排序是它自动为您处理的许多事情之一。 认真地说,您永远不会后悔使用ObjectListView而不是普通的ListView。 ObjectListView主页 ObjectListView Nuget软件包 回答2 忘记您的自定义分类器。 重新开始使用以下页面上的代码。
  • Kotlin和不可变集合?(Kotlin and Immutable Collections?)
    问题 我正在学习Kotlin,并且看起来我可能希望在明年使用它作为我的主要语言。 但是,关于Kotlin是否具有不可变集合的研究一直在引起争议,我试图弄清楚是否需要使用Google Guava。 有人可以给我一些指导吗? 默认情况下是否使用不可变集合? 哪些运算符返回可变或不可变的集合? 如果没有,是否有实施这些计划的计划? 回答1 标准库中的Kotlin列表是只读的: interface List<out E> : Collection<E> (source) 元素的一般有序集合。 该接口中的方法仅支持对列表的只读访问;请参见图11。 通过MutableList接口支持读/写访问。 参数 E-列表中包含的元素的类型。 如前所述,还有MutableList interface MutableList<E> : List<E>, MutableCollection<E> (source) 元素的通用有序集合,支持添加和删除元素。 参数 E-列表中包含的元素的类型。 因此,Kotlin通过其接口强制执行只读行为,而不是像默认Java实现那样在运行时抛出异常。 同样,有一个MutableCollection , MutableIterable , MutableIterator , MutableListIterator , MutableMap和MutableSet
  • Filtering ListView with custom (object) adapter
    I'm trying to implement filtering of a ListView which is uses a custom object adapter, but I can't find any useful samples. The included code is very simplified, so no- keep in mind I can't use an regular ArrayAdapter. I have a EditText above the ListView, and when the user enters text in the EditText widget I would like to filter the ListView by the text written in the EditText. Any suggestions would be much appreciated! Here is the snippet from the activity class: public class management_objects extends Activity { private static List<User> UserList; private EfficientAdapter adapter = null
  • 检测地理位置是否在复杂的多边形中(Detect if geolocation is in complex polygon or not)
    问题 我们目前正在使用以下算法来检测某个地理点是否在复杂的多边形内。 除多边形与180度经线交叉以外,其他方法均能正常工作。 例如,在多边形160,65,0 160,15,0 -160,15,0 -160,65,0 160,65,0中未检测到点(-170,60) 看下面的图片:[Img] http://tinypic.com/r/14x2xl1 [/ img]我想要红色框中的所有内容。 不是黄框! public static bool IsCoordinateInPolygon(IList<KMLCoordinate> polygon, KMLCoordinate testPoint) { bool result = false; int j = polygon.Count - 1; for (int i = 0; i < polygon.Count; i++) { if (polygon[i].Latitude < testPoint.Latitude && polygon[j].Latitude >= testPoint.Latitude || polygon[j].Latitude < testPoint.Latitude && polygon[i].Latitude >= testPoint.Latitude) { if (polygon[i].Longitude +
  • C#:System.Object与泛型(C#: System.Object vs Generics)
    问题 我很难理解何时使用对象(装箱/拆箱)与何时使用泛型。 例如: public class Stack { int position; object[] data = new object[10]; public void Push (object o) { data[position++] = o; } public object Pop() { return data[--position]; } } VS。 public class Stack<T> { int position; T[] data = new T[100]; public void Push(T obj) {data[position++] = obj; } public T Pop() { return data[--position]; } } 我应该使用哪个,在什么条件下使用? 似乎使用System.Object方式,我可以拥有当前居住在我的Stack中的各种类型的对象。 所以这不是总是可取的吗? 谢谢! 回答1 始终使用泛型! 使用对象的结果进行强制转换操作和值类型的装箱/拆箱。 由于这些原因,泛型更快,更优雅(无需强制转换)。 而且-主要原因-您不会使用泛型获得InvalidCastException 。 因此,泛型更快,并且在编译时可见错误。 System.Object表示运行时异常和强制转换
  • 使用自定义(对象)适配器过滤ListView(Filtering ListView with custom (object) adapter)
    问题 我正在尝试对使用自定义对象适配器的ListView进行过滤,但是找不到任何有用的示例。 包含的代码非常简化,因此请记住,我不能使用常规的ArrayAdapter。 我在ListView上方有一个EditText,当用户在EditText小部件中输入文本时,我想用EditText中编写的文本过滤ListView。 我们欢迎所有的建议! 这是活动类的摘录: public class management_objects extends Activity { private static List<User> UserList; private EfficientAdapter adapter = null; private ListView objectListView = null; private EditText SearchText = null; private static class EfficientAdapter extends BaseAdapter implements Filterable{ private LayoutInflater mInflater; public EfficientAdapter(Context context) { mInflater = LayoutInflater.from(context); } public int
  • C ++ RTTI可行示例(C++ RTTI Viable Examples [closed])
    问题 从目前的情况来看,这个问题不适合我们的问答形式。 我们希望答案得到事实,参考或专业知识的支持,但是这个问题可能会引起辩论,争论,民意测验或进一步的讨论。 如果您认为此问题可以解决并且可以重新提出,请访问帮助中心以获取指导。 8年前关闭。 我熟悉C ++ RTTI,并发现了有趣的概念。 仍然存在许多滥用它的方法,而不是正确使用它的方法(想到的是RTTI-switch恐惧)。 作为开发人员,我发现(并使用)它只有两种可行的用途(更确切地说是一半)。 您能否分享一些RTTI是解决问题的可行方法,包括示例代码/伪代码? 注意:其目的是建立一个可供初级开发人员参考,批评和学习的可行示例库。 编辑:您会发现使用C ++ RTTI的以下代码 // A has a virtual destructor (i.e. is polymorphic) // B has a virtual destructor (i.e. is polymorphic) // B does (or does not ... pick your poison) inherits from A void doSomething(A * a) { // typeid()::name() returns the "name" of the object (not portable) std::cout << "a is [
  • How to tweak my tooltips in wxpython?
    I was trying to add a tooltip to show the full content of a truncated ObjectListView, until it turned out it had such a feature built-in: I tried making my own tool tips using wx.TipWindow, wx.PopupWindow and SuperToolTip, but none of them looked as 'native' as this one. While I'm aware of this wiki article that supposedly enables the tooltip for truncated wx.Listrctrls, I didn't really understand how to get it working. I also expect that it only works when something is truncated, whereas I'd like to be able to use it to display some more information. I guess the SuperToolTip comes close, but
  • 如何计算SQL varchar中某个子字符串出现的次数?(How do you count the number of occurrences of a certain substring in a SQL varchar?)
    问题 我有一列,其值的格式像a,b,c,d。 有没有一种方法可以在T-SQL中计算该值中的逗号数量? 回答1 我想到的第一种方法是通过用空字符串替换逗号并比较长度来间接地做到这一点。 Declare @string varchar(1000) Set @string = 'a,b,c,d' select len(@string) - len(replace(@string, ',', '')) 回答2 cmsjr答案的快速扩展,适用于具有多个字符的字符串。 CREATE FUNCTION dbo.CountOccurrencesOfString ( @searchString nvarchar(max), @searchTerm nvarchar(max) ) RETURNS INT AS BEGIN return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm) END 用法: SELECT * FROM MyTable where dbo.CountOccurrencesOfString(MyColumn, 'MyString') = 1 回答3 您可以将字符串的长度与删除逗号的长度进行比较: len(value) - len(replace(value,',',''
  • LINQ .Cast()扩展方法失败,但(类型)对象有效(LINQ .Cast() extension method fails but (type)object works)
    问题 为了在某​​些LINQ到SQL对象和DTO之间转换,我们在DTO上创建了显式的强制转换运算符。 这样,我们可以执行以下操作: DTOType MyDTO = (LinqToSQLType)MyLinq2SQLObj; 这很好。 但是,当您尝试使用LINQ .Cast()扩展方法进行强制转换时,它抛出无效的强制转换异常,提示无法将类型Linq2SQLType强制转换为DTOType类型。 即下面的行不通 List<DTO.Name> Names = dbContact.tNames.Cast<DTO.Name>() .ToList(); 但是下面的工作正常: DAL.tName MyDalName = new DAL.tName(); DTO.Name MyDTOName = (DTO.Name)MyDalName; 并且下面也可以正常工作 List<DTO.Name> Names = dbContact.tNames.Select(name => (DTO.Name)name) .ToList(); 为什么.Cast()扩展方法抛出无效的强制转换异常? 过去,我已经以这种方式多次使用.Cast()扩展方法,当您将类似基本类型的内容转换为派生类型时,它可以正常工作,但是当对象具有显式转换运算符时会失败。 回答1 Cast<>扩展方法不适用于用户定义的转换。
  • Does casting an Object in C# always return a Reference to the initial object
    I'm currently doing a project in C# working with windows forms. During the course of it, I did the following void HideButtons(object sender, EventArgs e) { Button hider = ((Button)sender); foreach(Button tohide in hider.Parent.Controls) tohide.Hide(); hider.Show(); hider.Text = "UnHide"; hider.Click -= new EventHandler(HideButtons); hider.Click += new EventHandler(ShowButtons); } The purpose of this code is to have a button which hides all the other buttons in the container it's in except itself, and then turn into an Unhide button which does the same thing in reverse. Now, that's all well and