VB.net修改代码解决XtraGridView列值存入TextEdit末尾带逗号问题
解决XtraGridView列值拼接末尾多余逗号问题
你的问题出在循环中每一次拼接都添加了, ,包括最后一个元素,导致末尾多出逗号。以下几种修改方案可以解决:
方案1:用列表收集值后拼接(推荐)
先把所有有效单元格值收集到列表中,再用String.Join直接生成带分隔符的字符串,简洁高效还能避免空值问题:
Dim values As New List(Of String)() For i = 0 To GridView1.RowCount - 1 Dim cellValue = GridView1.Columns.View.GetRowCellValue(i, "Names") If cellValue IsNot Nothing Then ' 可选:跳过空值 values.Add(cellValue.ToString()) End If Next textEdit1.Text = String.Join(", ", values)
方案2:循环中判断是否为最后一行
在循环里检查当前是否是最后一行,只有非最后一行才添加分隔符:
textEdit1.Text = "" For i = 0 To GridView1.RowCount - 1 Dim cellValue = GridView1.Columns.View.GetRowCellValue(i, "Names") If cellValue IsNot Nothing Then textEdit1.Text += cellValue.ToString() ' 不是最后一行时才添加逗号和空格 If i <> GridView1.RowCount - 1 Then textEdit1.Text += ", " End If End If Next
方案3:拼接后移除末尾多余分隔符
如果不想改动原有循环逻辑,可以在拼接完成后去掉末尾的, :
textEdit1.Text = "" For i = 0 To GridView1.RowCount - 1 Dim cellValue = GridView1.Columns.View.GetRowCellValue(i, "Names") If cellValue IsNot Nothing Then textEdit1.Text += cellValue.ToString() + ", " End If Next ' 移除末尾的", "(如果存在) If textEdit1.Text.EndsWith(", ") Then textEdit1.Text = textEdit1.Text.Substring(0, textEdit1.Text.Length - 2) End If
内容的提问来源于stack exchange,提问作者DeveloperGuy
相关产品推荐
相关产品推荐

