我有一个DataGridView与包含数据的数据库文件中的单元格.基本上,我想从DataGridView中的选定单元格中获取文本,并在单击按钮时将其显示在文本框中.按钮单击事件的代码是:
Private Sub Button1_Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles Button1.Click Dim SelectedThings As String = DataGridView1.SelectedCells.ToString TextBox1.Text = SelectedThings End Sub
但是在TextBox1中,我得到:
System.Windows.Forms.DataGridViewSelectedCellCollection
我觉得它并不像看起来那么简单.我是一名学习VB.NET的C开发人员.
DataGridView.SelectedCells
是单元格的集合,因此它不像在其上调用ToString()那么简单.您必须循环遍历集合中的每个单元格,并获取每个单元格的值.
以下将创建所有选定单元格值的逗号分隔列表.
C#
TextBox1.Text = ""; bool FirstValue = true; foreach(DataGridViewCell cell in DataGridView1.SelectedCells) { if(!FirstValue) { TextBox1.Text += ","; } TextBox1.Text += cell.Value.ToString(); FirstValue = false; }
VB.NET(Translated来自上面的代码)
TextBox1.Text = "" Dim FirstValue As Boolean = True Dim cell As DataGridViewCell For Each cell In DataGridView1.SelectedCells If Not FirstValue Then TextBox1.Text += "," End If TextBox1.Text += cell.Value.ToString() FirstValue = False Next