将文本从文本框发送到datagrid

时间:2014-04-12 14:48:02

标签: vb.net datagrid

我的表单上有文本框,我希望将文本发送到数据网格。我写了以下内容:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim itemName As String = txtItem.Text
    Dim qty As Double = CDbl(txtQTY.Text)
    Dim price As Double = CDbl(txtPrice.Text)
    Dim Total As Double = price * qty

    txtTotal.Text = Convert.ToString(Total)

    Dim row As Integer = grdNewInvoice.Rows.Count

    Dim data As TextBox() = New TextBox() {txtItem, txtQTY, txtPrice, txtTotal}
    grdNewInvoice.Rows.Add()

    For i As Integer = 0 To data.Length - 1
        grdNewInvoice(i, row).Value = data(0)

    Next


End Sub

但是我在datagrid行上得到以下内容:System.Windows.Forms.TextBox, Text: [textbox string]

我也尝试了以下代码,以确保我的数据网格设置没有任何问题:

'grdNewInvoice.Rows(0).Cells(0).Value = itemName
    'grdNewInvoice.Rows(0).Cells(1).Value = qty
    'grdNewInvoice.Rows(0).Cells(2).Value = price
    'grdNewInvoice.Rows(0).Cells(3).Value = Total

工作正常,文本按预期进入,但由于我将在datagrid上写入多行,我将需要使用循环。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是使用字符串数组列表。

Dim row As Integer = grdNewInvoice.Rows.Count

Dim data As New List(Of String())
data.Add({txtItem.Text, txtQTY.Text, txtPrice.Text, txtTotal.Text})
data.Add({"Item2", "qtr2", "price2", "total2"})
data.Add({"Item3", "qty3", "price3", "total3"})

For i As Integer = 0 To data.Count - 1
    grdNewInvoice.Rows.Add(data(i))
Next