c#从具有多个值的字典中填充listview

时间:2014-01-05 16:29:05

标签: c# listview dictionary

我有一个包含多个值的词典,我想用它来填充列表视图。

我得到“ArgumentOutOfRangeException未处理”,“invalidArgument =值'1'对'index'无效。

这是我希望足够的代码:

public partial class frmResultList : Form
{

    public class MyLookupCustList
    {
        public string sEstNum { get; set; }
        public string sLName  { get; set; }
        public string sFName  { get; set; }
        public string sCity   { get; set; }
    }

    public frmResultList(int iMyCount, Dictionary<string, frmResultList.MyLookupCustList> MyDictList)
    {
        InitializeComponent();
        fillListView(iMyCount, MyDictList);
    }

    public void fillListView(int iMyCount, Dictionary<string, frmResultList.MyLookupCustList> MyDictList)
    {

        listView1.Clear();

        ListViewItem item;

        for (int i = 0; i < iMyCount; i++)
        {
            listView1.Items.Clear();
            var o = MyDictList[i.ToString()];
            var myListViewItem = new ListViewItem();

            myListViewItem = this.listView1.Items.Add(i.ToString());
            myListViewItem.SubItems[1].Text = o.sEstNum;
            myListViewItem.SubItems[2].Text = o.sLName;
            myListViewItem.SubItems[3].Text = o.sFName;
            myListViewItem.SubItems[4].Text = o.sCity;

            listView1.Items.Add(myListViewItem);

        }

        listView1.View = View.Details;         
        listView1.Show();
        listView1.Refresh();


    }      

当我尝试插入第一个SubItem时,我得到了异常 这里===&gt; myListViewItem.SubItems [1] .Text = o.sEstNum; 请帮助,我需要解决这个问题?

1 个答案:

答案 0 :(得分:0)

您正在尝试使用索引[1]更新项目,该项目尚不存在,您需要先创建它。您尝试访问的子项也会发生相同的情况 - 2,3,4 所以你需要有逻辑来检查项目是否先存在,是否确实更新,否则添加它。