Datagridview中的项目正在被另一个项目替换

时间:2010-03-08 13:48:30

标签: vb.net

当我在datagridview中添加第一项时,它可以,但是当我添加第二项时,它会替换最后添加的项目。 这是我的代码 Private Sub add()

    Dim i As Integer
    For i = 0 To DataGridView1.Rows.Count - 1
        'DataGridView1.Rows.Add()
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("TransID").Value = txttrans.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("ProductCode").Value = txtprodcode.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("ProductName").Value = cmbprodname.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("Quantity").Value = txtqty.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("Price").Value = txtprc.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("Amount").Value = txtat.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("CustomerName").Value = txtcust.Text
        DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("Date1").Value = txtdate.Text

    Next i


End Sub

这是在我的ADD按钮中:

Private Sub btnadd_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)处理btnadd.Click

    Try
        add()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    Dim total As Integer

    For Each row As DataGridViewRow In DataGridView1.Rows

        total += row.Cells("Amount").Value

    Next

    txtamt.Text = total

2 个答案:

答案 0 :(得分:0)

这应该(和其他行)

DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("TransID").Value = txttrans.Text

不是

DataGridView1.Rows(i).Cells("TransID").Value = txttrans.Text

因为否则你只是添加行DataGridView1.RowCount - 1

答案 1 :(得分:0)

尝试以下方法。使用您需要的数据结构创建数据表。我提供了一个小例子。数据列数组包含列信息。 dt.columns.addRange将列设置为所需的列名结构。 dt.newRow()方法返回一个空行,但包含必要的模式,这样您就不会收到错误。添加完所有必需的行后,可以使用row [“columnName”]

引用数据表中的行

使用datagridview.datasource = dt将datagrid绑定到datatable对象。

  public Form1()
    {
        DataColumn column0 = new DataColumn("TransID");
        DataColumn column1 = new DataColumn("Price");
        DataColumn column2 = new DataColumn("Quantity");

        columns[0] = column0;
        columns[1] = column1;
        columns[2] = column2;

        DataTable dt = new DataTable();
        dt.Columns.AddRange(columns);

        //Creates a datarow object based on the dataable's schema
        DataRow row = dt.NewRow();

        row["TransID"] = "Transaction Text";
        row["Price"] = "Price Text";
        row["Quantity"] = "Quantity";

        //Add the row to the dataTable
        dt.Rows.Add(row);

        dataGridView1.DataSource = dt;
    }