我在WFA C#中有两种形式。
FORM1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
if (checkBox1.Checked == true)
{
f2.intr = checkBox1.Text;
}
if (checkBox2.Checked == true)
{
f2.intr2 = checkBox2.Text;
}
if (checkBox3.Checked == true)
{
f2.intr3 = checkBox3.Text;
}
if (checkBox4.Checked == true)
{
f2.intr4 = checkBox4.Text;
}
if (checkBox5.Checked == true)
{
f2.intr5 = checkBox5.Text;
}
f2.ShowDialog();
}
}
}
FORM2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form2 : Form
{
public string gen, intr, intr2, intr3, intr4, intr5;
public string interest
{
get { return intr; }
set { intr = value; }
}
public string interest2
{
get { return intr2; }
set { intr2 = value; }
}
public string interest3
{
get { return intr3; }
set { intr3 = value; }
}
public string interest4
{
get { return intr4; }
set { intr4 = value; }
}
public string interest5
{
get { return intr5; }
set { intr5 = value; }
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = "Interests: " + interest + "\n" + interest2 + "\n" + interest3 + "\n" + interest4 + "\n" + interest5;
}
}
}
我在组框中有5个复选框。这会将所选项目输出到label1。当我选中所有复选框时,输出看起来像这样:
art
science
math
history
sports
每当我随机选中复选框时,我会检查艺术和历史。输出是这样的:
art
history
它留下两个空格。
在form1的设计中,组框内有checkbox1,checkbox2,checkbox3,checkbox4,checkbox5。 在form2的设计中,只有label1。 如何在一行中用逗号分隔所选项目? 我是c#helpp的新手。
答案 0 :(得分:4)
您可以将所有兴趣放在数组中:
string[] interests = { interest, interest2, interest3, interest4, interest5 };
然后你可以删除未选择的那些:
string[] selectedInterests = interests.Where(str => !String.IsNullOrEmpty(str)).ToArray();
最后,您可以将它们合并为一个字符串:
label1.Text = String.Join(", ", selectedInterests);