从文本框更新字符串

4
在我正在制作的程序中,我在设置中创建了一个名为“Tickers”的字符串。其范围是Application,值为“AAPL,PEP,GILD”(不带引号)。
我有一个RichTextBox,名为InputTickers,用户应该在其中输入股票代码,例如AAPL、SPLS等。当他们点击InputTickers下方的按钮时,我需要获取Settings.Default["Tickers"]。接下来,我需要检查他们输入的股票代码是否已经在“Tickers”列表中。如果没有,在列表中添加。
添加完之后,我需要将其转换回Tickers字符串以再次存储在Settings中。
由于我还在学习编程,这是我完成的最佳猜测,但我无法想出如何正确地完成此操作。
private void ScanSubmit_Click(object sender, EventArgs e)
{
    // Declare and initialize variables
    List<string> tickerList = new List<string>();


    try
    {
        // Get the string from the Settings
        string tickersProperty = Settings.Default["Tickers"].ToString();

        // Split the string and load it into a list of strings
        tickerList.AddRange(tickersProperty.Split(','));

        // Loop through the list and do something to each ticker
        foreach (string ticker in tickerList)
        {
            if (ticker !== InputTickers.Text)
                 {
                     tickerList.Add(InputTickers.Text);
                 }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

1
很抱歉,您不能在运行时保存应用程序范围的设置。请参阅:http://msdn.microsoft.com/en-us/library/bb397755.aspx - Dave R.
2个回答

0

试着喜欢这个,

 foreach (string ticker in tickerList)
    {
        if (InputTickers.Text.Split(',').Contains(ticker))
             {
                 tickerList.Add(InputTickers.Text);
             }
    }

如果您的输入字符串中有空格,

        if (InputTickers.Text.Replace(" ","").Split(',').Contains(ticker))
         {

         }

0

你可以使用针对集合的LINQ扩展方法,这将带来更简洁的代码。首先,将字符串从设置中拆分并将项目添加到集合中。其次,还要拆分(你可能忘了)来自文本框的字符串并添加那些项目。第三,使用扩展方法获取不同的列表。

// Declare and initialize variables
List<string> tickerList = new List<string>();

    // Get the string from the Settings
    string tickersProperty = Settings.Default["Tickers"].ToString();

    // Split the string and load it into a list of strings
    tickerList.AddRange(tickersProperty.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
    tickerList.AddRange(InputTickers.Text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

    Settings.Default["Tickers"] = String.Join(',', tickerList.Distinct().ToArray());
    Settings.Default["Tickers"].Save();

嗯,对我来说看起来不错,所以我试了一下。其中有些部分不起作用,所以我一直在谷歌上搜索。似乎无法弄清楚如何修复它。当前上下文中不存在SplitOptions。让我们先尝试解决这个问题。我是否缺少一个特殊的命名空间?如果是这样,我很难找到它。 - BigBlackBunny
使用VisualStudio的智能感知,您将找到正确的版本。我最初在没有使用VisualStudio的情况下编写了我的答案。现在我已经检查并纠正了上面的代码/方法。请查看。 - Matthias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接