Document Upload to SharePoint with VB.NET - sql

At my company we have an initiative that allows users to submit "Winning Ideas". There is a form to fill out, and the user can upload documents on the form. The ideas are voted on by other employees, reviewed by a committee, and the user has the ability to win cash prizes and have their idea implemented in the company.
I created a custom webpart using ASP.NET that allows users to insert a row into a SQL table, and add documents to a SharePoint document list. The list of documents they upload is added to a field in the SQL table, and displayed as hyperlinks on the .aspx page.
Here are some of the issues I have seen with the document upload:
- Document is not uploaded at all.
- Document is uploaded, but not checked in.
- Document is uploaded and checked in, but not linked to a record (the field did not update in SQL).
- If adding multiple documents, both documents are uploaded but the content of the first document is repeated for all documents.
- Multiple entries are created with the Insert statement.
I can't figure out if this is a problem with my SQL or my VB. Is there a better way I should be doing this? Any help would be appreciated.
My current environment is as such:
- SharePoint 2013
- SQL Server 2012
- Microsoft Visual Studio Professional 2013
Partial Public Class WinningIdeasFormUserControl
Inherits UserControl
Public conn As SqlConnection
Public strDatabase As String
Public MyUserInfo As SPUser
Public strFiles As String
Public IdeaId As String
Public uploads As HttpFileCollection
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
'reference to file collection that was sent by the browser request'
uploads = HttpContext.Current.Request.Files
Try
conn = New SqlConnection(strDatabase)
Dim cmd As SqlCommand = New SqlCommand()
strFiles = ""
'SQL command to insert results into the database'
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO [WinningIdeas] (Title, Idea, Submitter, SPUserID) OUTPUT INSERTED.ID VALUES (#Title, #Idea, #Submitter, '" & MyUserInfo.ID & "')"
cmd.Parameters.AddWithValue("#Title", txtTitle.Text)
cmd.Parameters.AddWithValue("#Idea", txtIdea.InnerText)
cmd.Parameters.AddWithValue("#Submitter", MyUserInfo.Name)
'confirms that the database has been updated'
cmd.Connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
'set IdeaId to the output of the record that was just added (ID it was assigned in database)'
IdeaId = reader(0).ToString
cmd.Connection.Close()
cmd.Connection = Nothing
If uploads.Count > 1 Then
Try
'if the user uploaded documents, make sure we add them'
uploadDocuments()
Catch ex As Exception
Span1.InnerHtml = "An error has occurred while trying to upload your document(s). Please contact WinnDESK#winnco.com for more information. " & ex.Message & "."
End Try
ElseIf (reader.RecordsAffected = 1) Then 'if a record has been successfully created'
SendEmail()
Response.Redirect("/Pages/Submitted.aspx?IdeaId=" & IdeaId)
End If
Catch ex As Exception
'change the <span> to show the error message'
Span1.InnerHtml = ex.Message
End Try
End Sub
Public Sub uploadDocuments()
'upload files'
For i As Integer = 0 To (uploads.Count - 1)
Dim fileSize As Int64
fileSize = uploads(i).ContentLength
'get the file name from whichever file we are currently saving'
Dim filName As String = System.IO.Path.GetFileName(uploads(i).FileName)
'TODO: Size exception is bringing the user to an exception page. catch as my exception'
'make sure there are no empty files, make sure file is less than 50MB'
If (fileSize > 0 And fileSize < 52428800) Then
Dim spfile As SPFile = SPContext.Current.Web.Files.Add("/Documents/User%20Uploads/" + IdeaId + "_" + filName, FileField.PostedFile.InputStream)
spfile.CheckIn("Checked in by " & MyUserInfo.Name & " for Idea " & IdeaId, SPCheckinType.MajorCheckIn)
spfile.Publish("Published by " & MyUserInfo.Name & " for Idea " & IdeaId)
'separate files with a ";" in the database'
strFiles = strFiles + IdeaId + "_" + filName + ";"
Else
Throw New Exception("Your file, " & filName & ", was not uploaded correctly due to its size.")
End If
Next
Try
conn = New SqlConnection(strDatabase)
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "UPDATE WinningIdeas SET Documents = #Documents WHERE ID = " & IdeaId
cmd.Parameters.AddWithValue("#Documents", strFiles)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
cmd.Connection = Nothing
Response.Redirect("/Pages/Submitted.aspx?IdeaId=" & IdeaId)
Catch ex As Exception
'change the <span> to show the error message'
Span1.InnerHtml = ex.Message
End Try
End Sub

Related

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed

I am having a problem with a customer service module which is in a different solution. the problem I think is in my method of calling or getting a connection
here is my class called DBConnForAccess
Imports System.Data.OleDb
Imports System.Data.Odbc
Public Class DBConnForAccess
Dim Conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim Trans As OleDbTransaction
Public Function DBConnect(ByVal filePath As String, pass As String)
Try
' open Database
'Conn = New SqlConnection("Data Source=" + ServerName + "\" + DBName + ";User ID=" + DBUsername + ";Password=" + DBPassword + ";Initial Catalog= '" + TB + "'")
Conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Jet OLEDB:Database Password=" + pass + ";")
' "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;"
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
' create transaction
Trans = Conn.BeginTransaction
Return "Ok"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Sub ExecuteSQL(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
'execute the sql
CMD.ExecuteNonQuery()
End Sub
Public Sub commit()
Me.Trans.Commit()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub rollback()
Me.Trans.Rollback()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub CloseDB()
Me.Conn.Close()
Me.Conn.Dispose()
Me.Trans.Dispose()
End Sub
Public Function ReadData(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
Dim R = CMD.ExecuteReader()
'Do While R.Read
'Loop
Return R
End Function
End Class
Here is the Sub I use to fetch Data:
Dim connection As String = txt_util.readFromTextFile("ConnStr_2.txt", 0) + "Billing.mdb"
'connection string is in a text file with text at line 0 as "C:\BILLSERV\"
Private Sub searchAccnt(ByVal SIN As String)
'clear other fields
Clear("Acct")
Try
AccntDetail.DBConnect("ConcessionairesAccnt")
'Dim RS = AccntDetail.ReadData("Select * From AllAccounts Where SIN=#0", txtSIN.Text.Trim)
Dim RS = AccntDetail.ReadData("Select * From viewCSFAccnt Where SIN=#0", SIN)
RS.Read()
If RS.Hasrows = 0 Then
MsgBox("Accounts not found. Check the SIN you Enter.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records not found.")
'txtAppNo.Focus()
Exit Sub
Else
'MsgBox("Accounts correct.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records found.")
txtZoneNo.Text = RS.Item("Zone").ToString
txtSeq.Text = RS.Item("SeqNo").ToString
txtAccntName.Text = RS.Item("AccountName").ToString
txtAccntAddress.Text = RS.Item("HouseNo").ToString + " " + RS.Item("BLDGName").ToString + " " + RS.Item("Street").ToString + _
" " + RS.Item("BRGY").ToString
txtMeterNo.Text = RS.Item("MeterNo").ToString
txtAccntStatus.Text = varA.AccntStatus(RS.Item("Status").ToString)
'Dim con = AccessAccnt.DBConnect(connection, "")
'If con <> "Ok" Then
' MsgBox("Cannot establish a Connection to the server.", MsgBoxStyle.Critical, "Connection Lost...")
'End If
Dim ZoneNo = "Z" + GetChar(txtZoneNo.Text, 1) + GetChar(txtZoneNo.Text, 2) + "B" + GetChar(txtZoneNo.Text, 3) + GetChar(txtZoneNo.Text, 4)
AccessAccnt.DBConnect(connection, "")
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
Acc.Read()
txtLastReading.Text = Acc.Item("LastReading").ToString
Acc.close()
AccessAccnt.CloseDB()
End If
RS.Dispose()
AccntDetail.CloseDB()
dbCounter.DBConnect("ConcessionairesAccnt")
Dim result = dbCounter.ReadData("Select Top 1 CSFNo From CSFMaster WHERE (CSFNo LIKE '%" & ctrDate() & "%') order by CSFNo Desc")
result.read()
If result.hasrows = 0 Then
txtTrackingNo.Text = ctrDate() & "-" & "000001"
Else
txtTrackingNo.Text = counter.CtrLastItemWithChar("ConcessionairesAccnt", "CSFNo", "CSFMaster", "WHERE (CSFNo LIKE '%" & ctrDate() & "%') ORDER BY CSFNo DESC", 5)
End If
dbCounter.CloseDB()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The Error is thrown here:
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
It Says:
System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.
The Other Parts of the Sub Works fine, The part where I fetch Data on my MSSQL Server database. The Problem lies in the Access data-Fetching Code.
I tried Using the code on another project (just the code where i fetch access data) I worked on other solutions. But I copy and paste my code on any form in this solution I keeps giving the Error.
I thought Maybe I closed the connection somewhere but this is the only instance I used this code in this entire project. (Just to get the last reading record.)
The Database is in the correct place (C:\BILLSERV)
I've Tried searching it here on SE but all I can see where suggestions about maybe forgetting to open the connection. I used this code before and this code works on my other solutions. I just cant seem to have it work here on this particular project. I wonder Why..
I tried running another project using this code and it works fine.
Is there a bug about Access connection on VB.net 2012, I have been using this code (DBConnForAccess Class) for about a year now and this is the first time I have encountered this error. btw I use Access 2003 because this database used to be for an old system created in VB6.
Lastly could this be because the solution came from another computer using a VB.Net Program same as mine. Because We work as a team here. Hope someone with a better knowledge on these systems could help. Thanks in advance.
EDIT
If a connection has been made, there should be a .ldb file in access which should appear. (I tested this on another project and an ldb file appear once a connection has been made, as we all know ldb file contains the data of the user using the db file.) I tried to re-run the system and while I'm using the system no ldb file was created.
Also,I thought Maybe I closed the connection somewhere but this is the only instance I opened a connection in access and which I used the code in this entire project. (Just to get the last reading record.)
So this is NOT a duplicate of “There is already an open DataReader…” Reuse or Dispose DB Connections? Just for clarifications
After a week of debugging and reading articles in the web.
We have found the culprit of the Error.
Seems that the Target CPU Option in Advance compiler Settings was change to AnuCPU.
We noticed this after we checked the other application projects we used.
Changing it Back to x86 solves the connection problem.
I wonder why this affected the connection to the access.
All is working fine now. thank you Plutonix and Steve for all your suggestions we'll be having a change in our codes.

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

A Generic Error occurred in GDI+ Saving Picturebox into ole database

I'm trying to save a picturebox into an ole database.
Here's my code :
Dim stream As New IO.MemoryStream
PictureBox1.Image.Save(stream, Imaging.ImageFormat.Jpeg)
Try
Dim query As String = "INSERT INTO Guestinfo ([GuestName],[Phone],[Idofguest],[Room],[Arrival],[Checkout],[Address],[IDImage]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Text & "','" & DateTimePicker2.Text & "','" & TextBox4.Text & "',(#IDImage))"
Dim command As New OleDbCommand
With command
.CommandText = query
.Parameters.AddWithValue("#Picture", stream.GetBuffer())
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("Saved Successfully!", MsgBoxStyle.Information)
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
In "A Generic Error occurred in GDI+" this error appear:
PictureBox1.Image.Save(stream, Imaging.ImageFormat.Jpeg)
By the way, my column type is Ole Object.
I hope someone help me ...
This application has an Open Button which will help you open any picture file to a PictureBox on the form using OpenFileDialog. You will see the path of the picture file in a disabled TextBox. When you click the update button the Picture's path is saved to an Access Database.
Follow the steps below to create a similar project for yourself:
* Create a new Visual Basic.net project. Select Windows Forms Application from New Project Dialog Box. Name this application whatever you want.
* Create the following with below mentioned properties:
- Form - (Name): sample, Text: FormPictureApplication
- PictureBox - (Name): PictureBox1, SizeMode: StretchImage
- Button - (Name): ButtonUpdate, Text: &Update
- Button - (Name): ButtonOpen, Text: &Open
- TextBox - (Name): TextBoxPictureFilePath, Enabled: False
Double Click the Form, insert the following code right above Public Class {...}:
Imports System.Data.OleDb
Imports System.IO
Imports Microsoft.Win32
Double Click ButtonOpen and insert the following code:
Dim img As String
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = Nothing
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
openFileDialog1.FileName = ""
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
TextBoxPictureFilePath.Text = ""
img = openFileDialog1.FileName
PictureBox1.Image = System.Drawing.Bitmap.FromFile(img)
TextBoxPictureFilePath.Text = openFileDialog1.FileName
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
Create a Microsoft Access Database in your convenient location and name it as Databasemikeoe2003PictureApplication.mdb
Create a table with the name Tablemikeoe2003PictureApplication and add following Columns to it:
Id - Datatype: Autonumber
PicturePath - DataType: Memo (as file paths can be considerably long at times)
Double Click the UpdateButton and insert the following code:
Try
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim mySQLString As String
myConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Databasemikeoe2003PictureApplication.mdb;")
myConnection.Open()
mySQLString = "INSERT INTO Tablemikeoe2003PictureApplication (PicturePath) VALUES('" & Replace$(TextBoxPictureFilePath.Text, "'", "''") & "')"
myCommand = New OleDbCommand(mySQLString, myConnection)
myCommand.ExecuteNonQuery()
PictureBox1.Image = Nothing
TextBoxPictureFilePath.Text = ""
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
End Try
Run the application, it should work as desired.

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub