如何防止在listview

时间:2017-06-28 12:12:33

标签: c# listview httpwebrequest

我通过webrequest从新闻网站获取数据并显示我的列表视图。当用户点击按钮时,首先我得到所有新闻并显示我的列表视图,再过15分钟用户点击按钮。如果新闻退出,我正在检查我的新闻列表,我正在显示消息框“没有新消息”。但如果有新闻将所有新闻列表再次列入listview。例如。第一次lisview计数是75。并且有2个新消息,通常我的列表视图应该是77.但listview显示152.我的错误在哪里。你能帮助我吗 ?

我的按钮点击事件

private void btnHurriyet_Click(object sender, EventArgs e)
    {
        Hurriyet hurriyet = new Hurriyet();

        List<ListViewItem> list = hurriyet.GetTagsHurriyet();


        foreach (var item in list)
        {

            listView1.Items.Add(item);
        }
    }

这是我的班级

public static Dictionary<string, Hurriyet> HurriyetHaberList = new Dictionary<string, Hurriyet>();

    public List<ListViewItem> GetTagsHurriyet()
    {

        XmlDocument xdoc = new XmlDocument();

        xdoc.Load("http://www.hurriyet.com.tr/rss/gundem");

        XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");

        if (el != null)
        {
            el.ParentNode.RemoveChild(el);
        }

        XmlNode Haberler = el.SelectSingleNode("channel");


        List<ListViewItem> listViewItems = new List<ListViewItem>();

        bool degismiMi = false;

        foreach (XmlNode haber in Haberler.SelectNodes("item"))
        {

            Hurriyet h = new Hurriyet();

            ListViewItem li = new ListViewItem();

            //li.Text = haber.SelectSingleNode("title").InnerText;
            h.Title = haber.SelectSingleNode("title").InnerText;



            if (haber.SelectSingleNode("description").InnerText.Contains("&gt;"))
            {
                var str1 = haber.SelectSingleNode("description").InnerText.IndexOf("&gt;");
                var str2 = haber.SelectSingleNode("description").InnerText.Substring(str1 + 4);

                //li.SubItems.Add(str2);
            }
            else
            {
                //li.SubItems.Add(haber.SelectSingleNode("description").InnerText);
                h.Description = haber.SelectSingleNode("description").InnerText;
            }

            h.Link = haber.SelectSingleNode("link").InnerText;
            //li.SubItems.Add(haber.SelectSingleNode("link").InnerText);

            var format = DateTime.Parse(haber.SelectSingleNode("pubDate").InnerText.ToString());


            //li.SubItems.Add(format.ToString());
            h.PubDate = format;


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(haber.SelectSingleNode("link").InnerText);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader stream = new StreamReader(response.GetResponseStream());

            string final_response = stream.ReadToEnd();


            string begenningKeyword = "<meta name=\"keywords\" content=\"";



            var tags = final_response.IndexOf(begenningKeyword);
            var final_response2 = final_response.Substring(tags + begenningKeyword.Length);
            var tagsBol = final_response2.IndexOf("\" />");

            var lastTags = final_response2.Substring(0, tagsBol);
            int yer1;

            if (lastTags != string.Empty)
            {
                h.Tags = lastTags;
                //li.SubItems.Add(lastTags);
            }

            else
            {
                yer1 = final_response.IndexOf("tagsContainer");

                if (yer1 == -1)
                {
                    continue;
                }
                else
                {
                    yer1 = final_response.IndexOf("tagsContainer");
                    int yer2 = final_response.IndexOf("</div>", yer1);

                    var tagDiv = final_response.Substring(yer1, yer2 - yer1);

                    List<string> listele = new List<string>();

                    for (int i = 0; i < tagDiv.Length; i++)
                    {
                        var firstSpan = tagDiv.IndexOf("<span>");
                        var firstSpan2 = tagDiv.IndexOf("<span itemprop=\"keywords\">");

                        if (firstSpan != -1)
                        {
                            var secondSpan = tagDiv.IndexOf("</a>", firstSpan);
                            var lastSpan = tagDiv.Substring(firstSpan, secondSpan - firstSpan);

                            var remo = lastSpan.Replace("<span>", "");
                            var remo2 = remo.Replace("</span>", "");

                            listele.Add(remo2);

                            tagDiv = tagDiv.Replace(lastSpan, "");
                        }
                        else if (firstSpan2 != -1)
                        {
                            var secondSpan = tagDiv.IndexOf("</a>", firstSpan2);
                            var lastSpan = tagDiv.Substring(firstSpan2, secondSpan - firstSpan2);

                            var remo = lastSpan.Replace("<span itemprop=\"keywords\">", "");
                            var remo2 = remo.Replace("</span>", "");

                            listele.Add(remo2);

                            tagDiv = tagDiv.Replace(lastSpan, "");
                        }
                        else
                            break;

                    }

                    string c = string.Empty;
                    foreach (var item in listele)
                    {
                        c += item + ",";
                    }

                    //li.SubItems.Add(c.Substring(0, c.Length - 1));
                    h.Tags = c.Substring(0, c.Length - 1);
                }
            }

            if (HurriyetHaberList.ContainsKey(haber.SelectSingleNode("link").InnerText) == false)
            {
                HurriyetHaberList.Add(haber.SelectSingleNode("link").InnerText, h);
                degismiMi = true;
                //listViewItems.Insert(0,li);
            }
        }


        if (!degismiMi)
        {
            MessageBox.Show("Haberlerde değişiklik olmadı");
        }

        else
        {
            listViewItems.Clear();

            foreach (var item in HurriyetHaberList.OrderByDescending(x => x.Value.PubDate).ToList())
            {
                ListViewItem lstItem = new ListViewItem();
                lstItem.Text = item.Value.Title;
                lstItem.SubItems.Add(item.Value.Description);
                lstItem.SubItems.Add(item.Value.Link);
                lstItem.SubItems.Add(item.Value.PubDate.ToString());
                lstItem.SubItems.Add(item.Value.Tags);

                listViewItems.Add(lstItem);

            }
        }

        return listViewItems;
    }

截图

enter image description here

3 个答案:

答案 0 :(得分:3)

问题在于您的代码

hurriyet.GetTagsHurriyet();

提供所有77个项目,然后将此结果添加到您的列表Control中,并使用以下代码

foreach (var item in list)
{
    listView1.Items.Add(item);
}

您需要清除listView1或确保方法GetTagsHurriyet()仅返回新项目。

所以要么执行以下操作:

private void btnHurriyet_Click(object sender, EventArgs e)
{
    Hurriyet hurriyet = new Hurriyet();
    List<ListViewItem> list = hurriyet.GetTagsHurriyet();

    listView1.Items.Clear(); //<-- added line
    foreach (var item in list)
    {
        listView1.Items.Add(item);
    }
}

或者在您的GetTagsHurriyet()方法中,只有在您的字典说它是新的时才填写列表:

if (HurriyetHaberList.ContainsKey(haber.SelectSingleNode("link").InnerText) == false)
{
    HurriyetHaberList.Add(haber.SelectSingleNode("link").InnerText, h);
    degismiMi = true;
    //listViewItems.Insert(0,li);

    //add items to listViewItems here and drop the code below
}

修改 基于以下评论:

这样的事情: (没有测试代码,删除了一些注释以使其更小也改变了一些东西在这里和那里)

private void btnHurriyet_Click(object sender, EventArgs e)
{
    Hurriyet hurriyet = new Hurriyet();
    List<ListViewItem> list = hurriyet.GetTagsHurriyet();

    if (!list.Any())
        MessageBox.Show("Haberlerde değişiklik olmadı");
    else
    {
        foreach (var item in list)
            listView1.Items.Add(item);
    }
}

public static Dictionary<string, Hurriyet> HurriyetHaberList = new Dictionary<string, Hurriyet>();
public List<ListViewItem> GetTagsHurriyet()
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load("http://www.hurriyet.com.tr/rss/gundem");
    XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");

    if (el != null)
        el.ParentNode.RemoveChild(el);

    XmlNode Haberler = el.SelectSingleNode("channel");
    List<Hurriyet> newHurriyets = new List<Hurriyet>();

    bool degismiMi = false;
    foreach (XmlNode haber in Haberler.SelectNodes("item"))
    {
        var link = haber.SelectSingleNode("link").InnerText;
        if (HurriyetHaberList.ContainsKey(link))
            continue;

        Hurriyet h = new Hurriyet();

        h.Title = haber.SelectSingleNode("title").InnerText;
        if (!haber.SelectSingleNode("description").InnerText.Contains("&gt;"))
            h.Description = haber.SelectSingleNode("description").InnerText;

        h.Link = link;

        var format = DateTime.Parse(haber.SelectSingleNode("pubDate").InnerText.ToString());
        h.PubDate = format;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            string final_response = stream.ReadToEnd();
            string begenningKeyword = "<meta name=\"keywords\" content=\"";

            var tags = final_response.IndexOf(begenningKeyword);
            var final_response2 = final_response.Substring(tags + begenningKeyword.Length);
            var tagsBol = final_response2.IndexOf("\" />");

            var lastTags = final_response2.Substring(0, tagsBol);
            int yer1;

            if (!string.IsNullOrEmpty(lastTags))
                h.Tags = lastTags;
            else
            {
                yer1 = final_response.IndexOf("tagsContainer");

                if (yer1 == -1)
                    continue;

                yer1 = final_response.IndexOf("tagsContainer");
                int yer2 = final_response.IndexOf("</div>", yer1);

                var tagDiv = final_response.Substring(yer1, yer2 - yer1);

                List<string> listele = new List<string>();
                for (int i = 0; i < tagDiv.Length; i++)
                {
                    var firstSpan = tagDiv.IndexOf("<span>");
                    var firstSpan2 = tagDiv.IndexOf("<span itemprop=\"keywords\">");

                    if (firstSpan != -1)
                    {
                        var secondSpan = tagDiv.IndexOf("</a>", firstSpan);
                        var lastSpan = tagDiv.Substring(firstSpan, secondSpan - firstSpan);
                        var remo = lastSpan.Replace("<span>", "");
                        var remo2 = remo.Replace("</span>", "");
                        listele.Add(remo2);

                        tagDiv = tagDiv.Replace(lastSpan, "");
                    }
                    else if (firstSpan2 != -1)
                    {
                        var secondSpan = tagDiv.IndexOf("</a>", firstSpan2);
                        var lastSpan = tagDiv.Substring(firstSpan2, secondSpan - firstSpan2);
                        var remo = lastSpan.Replace("<span itemprop=\"keywords\">", "");
                        var remo2 = remo.Replace("</span>", "");
                        listele.Add(remo2);

                        tagDiv = tagDiv.Replace(lastSpan, "");
                    }
                    else
                        break;
                }

                h.Tags = string.Join(",", listele);
            }
        }

        HurriyetHaberList.Add(link, h);
        newHurriyets.Add(h);
    }

    List<ListViewItem> listViewItems = new List<ListViewItem>();
    foreach (var item in newHurriyets.OrderByDescending(x => x.PubDate))
    {
        ListViewItem lstItem = new ListViewItem();
        lstItem.Text = item.Title;
        lstItem.SubItems.Add(item.Description);
        lstItem.SubItems.Add(item.Link);
        lstItem.SubItems.Add(item.PubDate.ToString());
        lstItem.SubItems.Add(item.Tags);

        listViewItems.Add(lstItem);
    }

    return listViewItems;
}

答案 1 :(得分:1)

您可以在填写前清除项目:

private void btnHurriyet_Click(object sender, EventArgs e)
{
    Hurriyet hurriyet = new Hurriyet();

    List<ListViewItem> list = hurriyet.GetTagsHurriyet();

    listView1.Items.Clear(); // Clear items
    foreach (var item in list)
    {
        listView1.Items.Add(item);
    }
}

否则你必须检查listView1是否没有你要添加的项目(不是通过引用,可能是某些属性?)。但是,这种情况不会处理删除项目

private void btnHurriyet_Click(object sender, EventArgs e)
{
    Hurriyet hurriyet = new Hurriyet();

    List<ListViewItem> list = hurriyet.GetTagsHurriyet();

    foreach (var item in list)
    {
        if(!IsItemPresent(item)) // You should implement this method somehow
            listView1.Items.Add(item);
    }
}

答案 2 :(得分:0)

在添加新项目之前,listView1应该清除。因为他们是旧的数据。 把这段代码放在ListView1.Clear();在开始循环之前。

listView1.Clear();

private void btnHurriyet_Click(object sender,EventArgs e)     {         Hurriyet hurriyet =新的Hurriyet();

    List<ListViewItem> list = hurriyet.GetTagsHurriyet();

listView1.Clear();

    foreach (var item in list)
    {

        listView1.Items.Add(item);
    }
}