0

ラベルを持っています。リストがあります。「label1.Text = match.Value;」を実行すると、ボタンをクリックするたびに変化する 1 つの文字列とは対照的に、リストの最後の項目が表示されます。コードは次のとおりです。

private void frontPageToolStripMenuItem_Click(object sender, EventArgs e)
    {
        const string url = "http://reddit.com/r/pics";
        var source = getSource(url);
        var regex = new Regex([regex removed]);
        var links = new List<string>();
        var titles = new List<string>();

        foreach (Match match in regex.Matches(source))
        {
            links.Add(match.Groups[1].Value);
            titles.Add(match.Groups[2].Value);

        }

        foreach (var title in titles)
        {
            label1.Text = title; /*it just shows the last 'title' in 'titles', I want it to start at the first, and go to the next title every time the event occurs (frontPageToolStripMenuItem_Click)*/ 
        }

    }

前もって感謝します!

4

4 に答える 4

4

クリック イベント ハンドラの外でリストを初期化する必要があります。FetchImageDataプログラムの開始時に呼び出されるメソッドを作成できます(おそらく、クラスのコンストラクターから呼び出します)。または、クリック イベントが最初に発生したときにリストと呼ぶこともできます。

private int clickCounter = 0;
private List<string> links;
private List<string> titles;

private void FetchImageData()
{
    links = new List<string>();
    titles = new List<string>();

    const string url = "http://reddit.com/r/pics";
    var source = getSource(url);
    var regex = new Regex([regex removed]);

    foreach (Match match in regex.Matches(source))
    {
        links.Add(match.Groups[1].Value);
        titles.Add(match.Groups[2].Value);
    }
}

ユーザーが要素の数よりも多くクリックした場合にどうなるかについては、まだ述べていません。1 つのオプションは、ラップアラウンドして最初からやり直すことです。%これは、演算子を使用して実現できます。

private void frontPageToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (titles == null) { FetchImageData(); }
    label1.Text = titles[clickCounter % titles.Count];
    clickCounter++;
}
于 2012-11-09T13:34:11.507 に答える
0

for ループが UI スレッド上にあるため、UI スレッドはラベルを更新する機会がありません。for ループをバックグラウンド スレッドに移動しても、ちらつきと最終的な文字列が表示される可能性が高くなります。文字列をテキスト ボックスに追加するか、Debug.writeLine を使用して出力するだけです。これにより、正しい文字列を読み取っていることがわかります。

ラベルを一度だけ変更するには、for ループでは行わないでください

于 2012-11-09T13:38:00.543 に答える
0

1)titlesグローバル変数であること

2)フォームのコンストラクターでこれを移動します

    const string url = "http://reddit.com/r/pics";
                var source = getSource(url);
                var regex = new Regex("<a class=\"title \" href=\"(.*?)\" >(.*?)<");

        titles = new List<string>();

                foreach (Match match in regex.Matches(source))
                {
                    links.Add(match.Groups[1].Value);
                    titles.Add(match.Groups[2].Value);

                }
label1.Text = first value of the titles

3) イベント ハンドラーは次のようになります。

private void frontPageToolStripMenuItem_Click(object sender, EventArgs e)
    {
            label1.Text = next value of the titles variable;

    }
于 2012-11-09T13:39:13.917 に答える