连接ListBox选择的项目

时间:2016-05-24 20:25:27

标签: c# arrays winforms listbox

我在WinForms .NET 4.5中有一个listBox。插件上我一直收到'NULL'异常,我不知道为什么。我TWEAK作为.dbml来自tbl_Tweak完成了数据集。我在某个地方遗失了某些东西而未能找到什么或在哪里。我希望新鲜,有经验的眼睛可以在这里发光。这是相关的代码。

插入方法:

public void InsertOrUpdateTweak(string recipename, string batchID, DateTime dtpTweak, int tempTweak, double specificGravityTweak, string tweakBox, string cbEventItems, int r_ID, string arrr)
        {
            TWEAKDataContext tdc = new TWEAKDataContext();
            if (dirtyTweak == true)
                try
               {
                GetEvents();

                tbl_Tweak log = new tbl_Tweak();
                log.recipename = recipeName;
                log.batchID = batchID;
                log.dtpTweak = DateTime.Now;
                log.tempTweak = tempTweak;
                log.specificGravityTweak = specificGravityTweak;
                log.tweakBox = tweakBox;
                log.cbEventItems = cbEventItems;

                tdc.tbl_Tweak.InsertOnSubmit(log);
                tdc.SubmitChanges();
            }
            catch (Exception ex)
            {
                throw ex;  //<== This is where it breaks
            }
            try
            {
                MessageBox.Show("You have not loaded and/or saved the current recipe data");
            }
                finally
                {
                    tdc.SubmitChanges();
                }
            }
    }

GetEvents方法,我尝试将列表框中的选定项目放入字符串中:

public string GetEvents()
{
        string[] arrr = new string[listBoxEvents.Items.Count];
        listBoxEvents.SelectedItems.CopyTo(arrr, 0);
        cbEventItems = string.Join("-", arrr);
        return cbEventItems;
}

我搜索过SO并发现了以下几种变体:

public string[] GetEvents()
{
String[] cbEventItems = new String[listBoxEvents.SelectedItems.Count];
for (int i = 0; i < totalEvents; i++)
{
   var arrr = String.Join(Environment.NewLine, listBoxEvents.SelectedItems.Cast<string>());
}
return arrr;
}

和...

public string[] GetEvents()
{
string[] arrr = new string[listBoxEvents.SelectedItems.Count];
for (int i = 0; i < listBoxEvents.SelectedItems.Count; i++)
arrr[i] = listBoxEvents.SelectedItems[i].ToString();

return arrr;
}

还有...

public string GetEvents()
{
    List<string> arrr = new List<string>(listBoxEvents.SelectedItems.Count);
    foreach (string listitem in listBoxEvents.SelectedItems)
    {
        cbEventItems = string.Join("-", arrr);
    }
    return cbEventItems;
}

1 个答案:

答案 0 :(得分:1)

看起来可能会混淆一个名为cbEventItems的方法参数和字段变量。字符串是不可变的,也可能导致问题。尝试从cbEventItems方法签名中删除InsertOrUpdateTweak参数,然后再进行操作。

同样看到GetEvents方法返回一个字符串,我会创建一个方法变量,然后使用它来使代码更具可读性。

public void InsertOrUpdateTweak(string recipename, string batchID, DateTime dtpTweak, int tempTweak, double specificGravityTweak, string tweakBox, int r_ID, string arrr)
        {
             ...
             string eventItems = GetEvents();
             ...
             log.cbEventItems = eventItems;
             ...
        }