vb.net – 从DataGridView中选择单元格获取文本

前端之家收集整理的这篇文章主要介绍了vb.net – 从DataGridView中选择单元格获取文本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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
原文链接:https://www.f2er.com/vb/255411.html

猜你在找的VB相关文章