januaryananda
januaryananda

Reputation: 407

Added new row to datagrid but the value keeps on the first row

I tried making simple program that add new row in my datagridview when I click a button and send a specific value to new added row. Here's the code

http://pastebin.com/mN5QwL1Z

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles Button2.Click
    Dim baris As Integer
    baris = 0
    perintah.Connection = koneksi
    perintah.CommandType = CommandType.Text
    perintah.CommandText = "select * from film where kode_film ='" & TextBox11.Text & "'"

    dr = perintah.ExecuteReader()
    If dr.HasRows = True Then
        dr.Read()
        DataGridView1.Rows.Add()
        DataGridView1.Rows(baris).Cells(0).Value = dr("kode_film")
        DataGridView1.Rows(baris).Cells(1).Value = dr("nama_film")
        DataGridView1.Rows(baris).Cells(2).Value = dr("stok")
        dr.Close()

    End If

    dr.Close()



End Sub

The problem is, each time I click the button, it do makes a new row in datagridview, but the value keeps on the first row and not inserted in the new added value.

Have googled so many times but haven't found the answer. Need your hand, guys. Sorry my bad English.

Upvotes: 0

Views: 93

Answers (2)

januaryananda
januaryananda

Reputation: 407

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles Button2.Click
Dim baris As Integer
baris = 0
perintah.Connection = koneksi
perintah.CommandType = CommandType.Text
perintah.CommandText = "select * from film where kode_film ='" & TextBox11.Text & "'"

dr = perintah.ExecuteReader()
If dr.HasRows = True Then
    dr.Read()
    DataGridView1.Rows.Add()
    DataGridView1.Rows(baris).Cells(0).Value = dr("kode_film")
    DataGridView1.Rows(baris).Cells(1).Value = dr("nama_film")
    DataGridView1.Rows(baris).Cells(2).Value = dr("stok")
    dr.Close()
    baris = baris + 1

End If

dr.Close()



End Sub

Had changed the value of baris but the value still on the first row and it replaces the previous value I inserted.

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54417

You're not changing the value of baris anywhere so you always get the row at index 0. The Add method returns the index of the new row so use that. Better still, use the overload of Add that takes the cell values as arguments, so you create and populate the row in a single line of code.

Upvotes: 1

Related Questions