Items are being replaced by another in the Datagridview
When I add the first item in the DataGridView it's OK but when I add the second one it replaces the last item added.
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
And this is in my ADDbutton:
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 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
Should this (and the other lines)
DataGridView1.Rows(DataGridView1.RowCount - 1).Cells("TransID").Value = txttrans.Text
not be
DataGridView1.Rows(i).Cells("TransID").Value = txttrans.Text
because otherwise you are just addint the row DataGridView1.RowCount - 1
.
Try the following. Create a datatable with with the data structue that you need. I provided a small example of what to do. The data column array contains the column information. dt.columns.addRange sets your columns to the desired column name structure. The dt.newRow() method returns an empty row but contains the necessary schema so that you won't get the error that you are getting. Once you have added all the rows necessary you can reference the rows in the datatable using row["columnName"]
Use datagridview.datasource = dt to bind the datagrid to the datatable object.
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;
}
精彩评论