简体   繁体   中英

How to add to a list in C# via button/textbox in a windows form

How to add to a list in C# via button/textbox in a windows form. I'm trying to add to my block sites list but does not seem to work , here are the two snippets below

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    List<string> BlockList = new List<string>();
    BlockList.Add("http://www.google.com");
    BlockList.Add("http://www.google.co.uk");
    BlockList.Add("http://www.bing.com");
    string[] BlockArray = BlockList.ToArray();
    for (int i = 0; i < BlockArray.Length; i++)
    {
        if (e.Url.Equals(BlockList[i]))
        {
            e.Cancel = true;
            MessageBox.Show("Booyaa Says No!", "NO NO NO", MessageBoxButtons.OK, MessageBoxIcon.Hand); // Block List Error Message
        }
    }
}

private void button6_Click_1(object sender, EventArgs e)
{
   BlockList.Add(textBox2.Text);
}

You need to add the BlockList as a member in the form class, not as a local variable inside a function. Then you will be able to use int i both functions.

Just add this member to the form class:

private List<string> BlockList = new List<string>() { "http://www.google.com", "http://www.google.co.uk", "http://www.bing.com" };

and change the webBrowser1_Navigating method to:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    string[] BlockArray = BlockList.ToArray();
    for (int i = 0; i < BlockArray.Length; i++)
    {
        if (e.Url.Equals(BlockList[i]))
        {
            e.Cancel = true;
            MessageBox.Show("Booyaa Says No!", "NO NO NO", MessageBoxButtons.OK, MessageBoxIcon.Hand); // Block List Error Message
        }
    }
}

You can also simplify the webBrowser1_Navigating method by replacing the loop over the BlockList list with the Contains method:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    if (BlockList.Contains(e.Url.ToString()))
    {
        e.Cancel = true;
        MessageBox.Show("Booyaa Says No!", "NO NO NO", MessageBoxButtons.OK, MessageBoxIcon.Hand); // Block List Error Message
    }
}

Your variable BlockList must be global.

You have only a local declaration like this

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

in your function "webBrowser1_Navigating"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM