Click here to Skip to main content
15,896,456 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Goodday!
I wanted to create a temporary gridview before saving.When I enter values on textboxs , click Add, then it will populate the gridview.

The problem:
1. When I have successfully added values for the first row, and add new values. It overwrites the first row values. I wanted to make the new values on the next row. Or just create a new row then show the new values that has been inputted from the textboxes.


Here is my code:

VB
Dim dt As New DataTable()

       dt.Columns.AddRange(New DataColumn(6) {New DataColumn("Code"), New DataColumn("Description"), New DataColumn("Specification"), New DataColumn("Availability"), New DataColumn("Storage Location"), New DataColumn("Quantity"), New DataColumn("Critical")})
       dt.Rows.Add(componentCodeTextbox.Text, DescriptionTextbox.Text, txt_specs.Text, cb_availability.SelectedItem, txt_location.Text, QuantityTextbox.Text, CriticalTextbox.Text)

       ViewState("dt") = dt
       TempGV.DataSource = TryCast(ViewState("dt"), DataTable)
       TempGV.DataBind()


End Sub


But has error in :
Dim dr As datarow = dt.NewRow()


ERROR: object null reference exception
do I have to add other code so that I could add new row?

Any help would be much appreciated. Thanks in advance.
Posted
Updated 9-Sep-14 22:22pm
v4
Comments
Gihan Liyanage 10-Sep-14 3:24am    
I am not familiar with vb.net but can you plz try this when adding new row to DT

Dim R As DataRow = dt.NewRow
R("Name") = txtName.Text
dt.Rows.Add(R)
DataGridView1.DataSource = dt
NekoNao 10-Sep-14 3:25am    
okay will try.
NekoNao 10-Sep-14 3:35am    
has error in dt.rows says "object null"
Gihan Liyanage 10-Sep-14 3:39am    
You should create dt first
Dim dt As datatable = New DataTable()
Then add newdata row to dt.
Gihan Liyanage 10-Sep-14 3:47am    
In your new code I can see the dt is on out of the scope where you have create the DT.

End If
Dim dr As datarow = dt.NewRow()

1 solution

This is my reference, and it solved my problem.

VB
Protected Sub BtnAddCourses_Click(sender As Object, e As EventArgs)
	Dim dt As datatable = New DataTable()
	If ViewState("ANYSTRING") Is Nothing Then
		dt.Columns.Add("COLUMNNAME1")
		dt.Columns.Add("COLUMNNAME2")
		dt.Columns.Add("COLUMNNAME3")
	Else
		dt = DirectCast(ViewState("ANYSTRING"), DataTable)
	End If
	Dim dr As datarow = dt.NewRow()
	dr("COLUMNNAME1") = TEXTBOX1.TEXT
	dr("COLUMNNAME2") = DROPDOWNLIST.SELECTEDVALUE
	dr("COLUMNNAME3") = TEXTBOX1.TEXT
	dt.Rows.Add(dr)
	ViewState("ANYSTRING") = dt
	GRIDVIEW.DataSource = dt
	GRIDVIEW.DataBind()
	GRIDVIEW.Visible = True
End Sub


CHECK ANSWER 2[^]
 
Share this answer
 
v6

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900