获得从DataGridView选定单元格文本
-
05-09-2019 - |
题
我有从包含数据的数据库文件细胞一个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
我想它并不像看起来那么简单。我是一个C语言开发刚学VB.NET。
解决方案
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 强>(翻译从码以上)
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
其他提示
尝试这种情况:
Dim i = Datagridview1.currentrow.index
textbox1.text = datagridview1.item(columnindex, i).value
它应该工作:)
简单地
MsgBox(GridView1.CurrentCell.Value.ToString)
Private Sub DataGridView1_CellClick(ByVal sender As System.Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellClick
MsgBox(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
End Sub
一个很多此页面上的答案仅仅适用于单个小区,并且OP要求的所有强>所选择的细胞中。
如果你想要的是单元格的内容,你不关心到所选择的实际单元引用,你可以这样做:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SelectedThings As String = DataGridView1.GetClipboardContent().GetText().Replace(ChrW(9), ",")
TextBox1.Text = SelectedThings
End Sub
当被点击Button1
,这将填补TextBox1
与所选择的小区的逗号分隔的值。
在此特定情况下,所述的ToString()将返回由SelectedCell属性retruned的对象的名称。(当前选择的细胞的集合)。
当一个对象具有用于的ToString没有具体implenetation()方法。
出现此现象的在我们的例子中,你所要做的就是迭代细胞的收集和积累其值的字符串。然后推入此字符串与文本框。
看看这里如何实现迭代:
或者,在情况下,你只需要第一入围卖出的值(或只是一个选择的小区,如果一个被选择)
TextBox1.Text = SelectedCells[0].Value.ToString();
两全其美的.....
Private Sub tsbSendNewsLetter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbSendNewsLetter.Click
Dim tmpstr As String = ""
Dim cnt As Integer = 0
Dim virgin As Boolean = True
For cnt = 0 To (dgvDetails.Rows.Count - 1)
If Not dgvContacts.Rows(cnt).Cells(9).Value.ToString() Is Nothing Then
If Not dgvContacts.Rows(cnt).Cells(9).Value.ToString().Length = 0 Then
If Not virgin Then
tmpstr += ", "
End If
tmpstr += dgvContacts.Rows(cnt).Cells(9).Value.ToString()
virgin = False
'MsgBox(tmpstr)
End If
End If
Next
Dim email As New qkuantusMailer()
email.txtMailTo.Text = tmpstr
email.Show()
End Sub
或,我们可以使用这样的
dim i = dgv1.CurrentCellAddress.X
dim j = dgv1.CurrentCellAddress.Y
MsgBox(dgv1.Item(i,j).Value.ToString())
不隶属于 StackOverflow