2015-11-29 41 views
0

我在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的设计中,在groupbox中有checkbox1,checkbox2,checkbox3,checkbox4,checkbox5。 在form2的设计中只有label1。 如何在一行中用逗号分隔所选项目? 我是新来的C#helpp。

+0

所有这些设置器和获取器都是多余的,你可以用'public string interest {get;组; }','(checkBox1.Checked == true)'与'(checkBox1.Checked)'相同' –

回答

4

你可以把所有的利益在一个数组:

string[] interests = { interest, interest2, interest3, interest4, interest5 }; 

然后,你可以删除非选择的:

string[] selectedInterests = interests.Where(str => !String.IsNullOrEmpty(str)).ToArray(); 

在最后你可以将它们合并成一个单一的字符串:

label1.Text = String.Join(", ", selectedInterests); 
+0

您可以删除selectedInterests的分配并直接在Join方法中执行该操作... –

+0

不,他不应该这样做。这样使用Debugger时,它更易读易维护。我们并不试图制作最短的代码,但最容易阅读和调试。 –

相关问题