簡體   English   中英

如何從C#WinForms的外部if語句訪問在if語句中創建的控件?

[英]How can I access control created within if-statement from outside if-statement in C# WinForms?

我正在將音樂播放列表從磁盤加載到C#ListView控件。 我正在使用ListViewGroups來分離專輯,並且播放列表中可以有多個專輯。

播放列表以以下文本格式保存:(我知道這不是最好的方法,但適用於此示例)

|album|name of album
track 1 fsdfsfasf.mp3
track 2 fdsgfgfdhhh.mp3
track 3 gfdgsdgsdfgs.mp3

將播放列表加載到ListView時,我會測試字符串“ | album |” 從行的開頭找到,並將該行用作組標題文本。 下面的代碼示例:

using (StreamReader reader = File.OpenText("playlist.txt"))
{
    while (reader.Peek() >= 0)
    {
        result = reader.ReadLine();

        if (result.Substring(0, 7) == "|album|")
        {
            ListViewGroup group = new ListViewGroup();
            group.Header = result.Substring(7);
            lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
        }

        else
        {
            ListViewItem item = new ListViewItem(result, 0, group);
            lstPlaylist.Items.Add(item);
        }
    }
}

如果是“ |專輯|” 找到字符串,然后創建新的ListViewGroup。 但是在else語句中無法訪問該組(我無法將項目分配給組),因為它不在范圍內。 如何在if語句內創建新的ListViewGroup並在if語句外使用它?

您需要在if語句外聲明變量,以便在else子句中可用。 您還需要處理在專輯之前找到曲目的情況,除非您已經驗證了源文件。

using (StreamReader reader = File.OpenText("playlist.txt"))
        {
            ListViewGroup group = null;
            while (reader.Peek() >= 0)
            {
                result = reader.ReadLine();
                if (result.Substring(0, 7) == "|album|")
                {
                    group = new ListViewGroup();
                    group.Header = result.Substring(7);
                    lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
                }

                else
                {
                    if (group != null)
                    {
                        ListViewItem item = new ListViewItem(result, 0, group);
                        lstPlaylist.Items.Add(item);
                    } 
                    else
                    {
                        // you are trying to add a track before any group has been created.
                        // handle this error condition
                    }
                }
            }
        }

您必須首先在if語句外聲明變量,然后在if語句內給它任何值。 如果要在if和else中使用相同的值,則在外部。

基本上發生的事情是,如果轉到代碼的else部分,則永遠不會生成該變量,因為該變量是在if部分中創建和初始化的。

祝好運!

查看您的邏輯,無論哪種情況,都需要初始化ListViewGroup 如果找到單詞“ |專輯|” 然后您還要分配一個屬性值。 因此,一個簡單的解決方法是將變量向上移動以增加其范圍:

ListViewGroup group = new ListViewGroup();//move to here
if (result.Substring(0, 7) == "|album|")
        {

            group.Header = result.Substring(7);
            lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
        }

        else
        {
            ListViewItem item = new ListViewItem(result, 0, group);//now group is initialized here as well
            lstPlaylist.Items.Add(item);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM