填充字符串数组与ListBox在C#中选定的项目#
问题描述:
我有一个ListBox有X数量(从9到90)的项目。我试图用列表框中选择的项目来填充(在按钮上单击)一个字符串数组。以下是我迄今为止填充字符串数组与ListBox在C#中选定的项目#
private void generateTam_Click(object sender, EventArgs e)
{
String sCombinedTam = "";
String sTamResponseStart = "Dear $contacts.name.first,@\[email protected]\nYour request has been received and [email protected]\nThe following actions were taken:@\n";
String sTamResponseEnd = "Thank you for choosing %company%, and have a great [email protected]\[email protected]\[email protected]\n%company%";
sTamResponseStart = sTamResponseStart.Replace("@\n", System.Environment.NewLine); //Replaces token @\n with NewLine
//Gets Actions Selected, Sends to Array
String[] sActionItemsSelected = new String[actionsListBox.Items.Count];
for (int x = 0; x < actionsListBox.Items.Count; ++x)
{
if (actionsListBox.GetSelected(x) == true)
{
actionsListBox.Items.CopyTo(sActionItemsSelected, 0);
}
}
//Gets Profiles Selected, Sends to Array
String[] sProfileItemsSelected = new String[profilesListBox.Items.Count];
for (int x = 0; x < profilesListBox.Items.Count; ++x)
{
if (profilesListBox.GetSelected(x) == true)
{
profilesListBox.Items.CopyTo(sProfileItemsSelected, x);
}
else if (profilesListBox.GetSelected(x) == false)
{
sProfileItemsSelected[x] = "";
}
}
//Combines strings for end response
for (int i = 0; i < sActionItemsSelected.Length; ++i)
{
sCombinedTam = sCombinedTam + sActionItemsSelected[i] + "@\n";
}
sCombinedTam = sCombinedTam.Replace("@\n", System.Environment.NewLine);
sTamResponseEnd = sTamResponseEnd.Replace("@\n", System.Environment.NewLine);
sCombinedTam = sTamResponseStart + sCombinedTam + sTamResponseEnd;
notesTextBox.Text = sCombinedTam;
//Outputs ENTIRE index ListBoxes not just selected items.
}
这个问题是到了最后,而不是设置notesTextBox.Text
的组合字符串只ListBox中选定的项目将其设置为组合字符串列表框EVERY选项。
任何帮助将不胜感激。
答
使用ListBox.SelectedItems
属性来获得一个字符串,由换行符字符串分离所有选定的项目(你可以删除最后一个for
循环,以及你的一些其他代码)。
您可以将所选项目的集合转换回任何类型;在你的情况下,一个字符串。
var selectedItems =
String.Join(Environment.NewLine, listBox1.SelectedItems.Cast<string>());
'sCombinedTam'的预期输出是什么? – jhyap
@jhyap 像这样的事情 '亲爱的$ contacts.name.first,@ \ n @ \ n您的要求已收到,并完成@ \ n该采取以下行动:@ \ n [插入动作来选择1] [Insert Action Selected 2] ... [插入操作选中的90] 感谢您选择%company%,祝您有美好的一天!! @ \ n @ \ n $ incidents.assigned.acct_id @ \ n%公司% ' 其中@ \ n被替换为新行。 – Cistoran