You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB中如何将两个Textbox的内容添加到DataGridView的同一列中

VB 实现两个TextBox内容添加至DataGridView同一列的方案

实现步骤

  • 先对两个输入框做内容合法性校验,避免插入无效空值
  • 依次将两个输入框的内容作为新行,写入DataGridView的目标列
  • 可根据需求选择追加至行末尾、或插入到指定行位置

核心实现代码

' 触发添加操作的按钮点击事件示例
Private Sub AddToGridBtn_Click(sender As Object, e As EventArgs) Handles AddToGridBtn.Click
    ' 非空校验,不需要可删除
    If String.IsNullOrEmpty(TextBox1.Text) OrElse String.IsNullOrEmpty(TextBox2.Text) Then
        MessageBox.Show("两个输入框均需填写内容")
        Return
    End If

    ' 方法1:直接追加新行到末尾,赋值第1列(列索引为0)
    DataGridView1.Rows.Add(TextBox1.Text)
    DataGridView1.Rows.Add(TextBox2.Text)

    ' 可选:添加完成后清空输入框
    TextBox1.Text = ""
    TextBox2.Text = ""
End Sub

特殊场景适配

注意:DataGridView的列索引从0开始计数,如果你要操作的第1列存在前置隐藏列,或者需要显式指定列赋值,可以用以下写法:

' 显式指定列赋值写法,适配自定义列结构的DataGridView
Dim row1 As DataGridViewRow = New DataGridViewRow()
row1.CreateCells(DataGridView1)
row1.Cells(0).Value = TextBox1.Text ' 0为目标列的索引,可自行修改
DataGridView1.Rows.Add(row1)

Dim row2 As DataGridViewRow = New DataGridViewRow()
row2.CreateCells(DataGridView1)
row2.Cells(0).Value = TextBox2.Text
DataGridView1.Rows.Add(row2)
  • 如果需要插入到指定行位置而非末尾,把Rows.Add方法替换为Rows.Insert(目标行索引, 行对象)即可

内容的提问来源于stack exchange,提问作者Sanjay Jarad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:15:04