2017-04-22 34 views
0

我想要允许特定的复选框,如果检查要合并的数据并插入datagridview单列。多个复选框的值到datagridview单列

表格正在添加如下列;

table.Columns.Add("Drinks", Type.GetType("System.Int32")) 

然后

Checkbox 1 = Coke 
Checkbox 2 = Pepsi 
Checkbox 3 = Fanta 

这是类的代码:

Dim Drinks As String 

每个复选框的与他们的文本一起以下代码;

Drinks = "Coke" 

生成信息的按钮如下;

table.Rows.Add(Drinks.ToString) 
    DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill 
    DataGridView1.RowTemplate.Height = 100 
    DataGridView1.AllowUserToAddRows = False 
    DataGridView1.DataSource = table 

因此,如果有人选择“Checkbox1 & Checkbox2”我怎样才能得到datagridview的列“饮料”,以显示焦炭&百事可乐?

回答

1

创建字符串的基础知识是创建一个列表(Of CheckBox),用它来查询选中哪个CheckBox控件。

Public Class Form1 
    Public checkBoxList As List(Of CheckBox) 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Dim values As String = "Drinks " & 
      String.Join(" ", checkBoxList _ 
      .Where(Function(cb) cb.Checked).Select(Function(cb) cb.Text)) 

     ' use values for placing into your DataGridView 

    End Sub 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     checkBoxList = New List(Of CheckBox) From {CheckBox1, CheckBox2, CheckBox3} 
    End Sub 
End Class 

组合框,我做DropDownStyle = DropDownList中,并确保一个项目被选中

Public Class Form1 
    Private comboBoxList As List(Of ComboBox) 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Dim values As String = "Food " & String.Join(" ", 
      comboBoxList.Select(Function(cb) cb.Text)) 
     Label1.Text = values 
    End Sub 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     comboBoxList = New List(Of ComboBox) From 
      { 
       ComboBox1, 
       ComboBox2, 
       ComboBox3, 
       ComboBox4 
      } 
     comboBoxList.ForEach(Sub(cb) 
           cb.DropDownStyle = ComboBoxStyle.DropDownList 
           cb.SelectedIndex = 0 
          End Sub) 
    End Sub 
End Class 

变化,我们不作出初步选择。

Public Class Form1 
    Private comboBoxList As List(Of ComboBox) 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Dim values As String = "Food " & String.Join(" ", 
      comboBoxList.Where(Function(cb) Not String.IsNullOrWhiteSpace(cb.Text)) _ 
      .Select(Function(cb) cb.Text)) 

     Label1.Text = values 
    End Sub 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     comboBoxList = New List(Of ComboBox) From 
      { 
       ComboBox1, 
       ComboBox2, 
       ComboBox3, 
       ComboBox4 
      } 
     comboBoxList.ForEach(Sub(cb) 
           cb.DropDownStyle = ComboBoxStyle.DropDownList 
          End Sub) 
    End Sub 
End Class 
+0

谢谢。如果我有各种类型的“饮料”列标题,该怎么办?例子Combobox 4,5,6是食物 – Chris

+0

首先你应该问一个新的问题,但我确实修改了我的答案,包括你的新问题的两个变体。 –

+0

你真了不起!我会尽快给你一个尝试。欣赏投入到响应中的时间和精力。 – Chris