473,385 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How to be able to insert text into the textboxs and for them to go into a database?

Hello

Basically I want to to be able to insert things into my textboxes on vb.net and for them to go into my microsoft access file and into the customers table when I click the save button. I tried doing it myself I didn't succeed my work kept on erroring with this:



Heres my code:

Expand|Select|Wrap|Line Numbers
  1. Public Class frmCustomers
  2.  
  3.     Private OleDbInsertCommand1 As System.Data.OleDb.OleDbCommand
  4.     Private OleDbConnection1 As System.Data.OleDb.OleDbConnection
  5.     Private OleDbDataAdapter1 As System.Data.OleDb.OleDbDataAdapter
  6.  
  7.  
  8.  
  9. Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
  10.  
  11.         OleDbInsertCommand1 = New System.Data.OleDb.OleDbCommand
  12.  
  13.         OleDbConnection1 = New System.Data.OleDb.OleDbConnection
  14.  
  15.         OleDbInsertCommand1.CommandText = "INSERT INTO [Customer] (forename, surname, dob, housenumber, address 1, address 2, postcode, contact)  VALUES ('" & txtForename.Text & "', '" & txtSurname.Text & "', '" & txtHousenumber.Text & "', '" & txtAddress1.Text & "', '" & txtAddress2.Text & "', '" & txtPostcode.Text & "', '" & txtContact.Text & "')"
  16.  
  17.         OleDbInsertCommand1.Connection = Me.OleDbConnection1
  18.  
  19.         OleDbConnection1.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; " _
  20.       & "Data Source=E:\Ian Griffiths\Kit-tactic.accdb"
  21.  
  22.         Try
  23.  
  24.             OleDbConnection1.Open()
  25.  
  26.             OleDbInsertCommand1.ExecuteNonQuery()
  27.  
  28.         Catch ex As OleDb.OleDbException
  29.  
  30.             MessageBox.Show(ex.ToString)
  31.  
  32.         End Try
  33.  
  34.         OleDbConnection1.Close()
  35.  
  36.     End Sub
  37.  
  38. End Class
Now my database is called: Kit-tactic.accdb
The fields I hold are: forename, surname, dob, housenumber, address 1, address 2, postcode, contact

Thanks for any help :)
Feb 26 '11 #1
8 1901
You can try:
DATABASE.Tables(TABLENAME).Rows(ROWNAME).Item(POST ION) = TEXTBOX.Text
Feb 26 '11 #2
So take out all the code and just try that?
Feb 26 '11 #3
Here is some code I used for a database app, it adds the new data to the data set then updates the database: (Bare in mind you still need to declare the objects and fill the data adapter)
Expand|Select|Wrap|Line Numbers
  1.         Dim cb As New OleDb.OleDbCommandBuilder(da)
  2.         Dim dsNewRow As DataRow
  3.  
  4.         dsNewRow = ds.Tables("CrystalDirectory").NewRow()
  5.         PrimaryKey = PrimaryKey + 1
  6.  
  7.         dsNewRow.Item("ID") = PrimaryKey
  8.         dsNewRow.Item("CrystalName") = txtCrystalName.Text
  9.         dsNewRow.Item("CrystalColour") = txtCrystalColour.Text
  10.         dsNewRow.Item("CrystalAppearence") = txtCrystalAppearance.Text
  11.         dsNewRow.Item("CrystalRarity") = txtCrystalRarity.Text
  12.         dsNewRow.Item("CrystalSource") = txtCrystalSource.Text
  13.         dsNewRow.Item("CrystalAttributes") = txtCrystalAttributes.Text
  14.  
  15.         ds.Tables("CrystalDirectory").Rows.Add(dsNewRow)
  16.  
  17.         da.Update(ds, "CrystalDirectory")
  18.  
  19.         MaxRows = MaxRows + 1
  20.  
  21.         If chbConfirmUpdate.Checked = True Then
  22.  
  23.             MsgBox("Your Data Has Been Saved!", , "Crystal ADDer Data Update")
  24.  
  25.         End If
Feb 26 '11 #4
Expand|Select|Wrap|Line Numbers
  1.  If chbConfirmUpdate.Checked = True Then
  2.  
  3. MsgBox("Your Data Has Been Saved!", , "Crystal ADDer Data Update")
  4.  
  5. End If  
I don't understand that bit of code there, what do I need to assign it as? Ive got the rest working but if I remove that section, I get these errors 'Warning 1 Variable 'da' is used before it has been assigned a value. A null reference exception could result at runtime. E:\Ian Griffiths\MyProgramNEW\MyProgram1\Form1.vb 36 49 MyProgram1' I get these errors for da, MaxRows and PrimaryKey
Feb 27 '11 #5
That if statement is just code I had, that if a check box was checked it would notify the user of the save. You should delete it. MaxRows and PrimaryKey are specific for my application you can delete it. All variable must be assigned a value before they can be accessed. So you are getting those errors because 'MaxRows = MaxRows +1' Cannot be called because it never had a value to begin with, you would need to give it a value at some point before you call it. eg, MaxRows = 5. You have to declare all the objects. EG:
Expand|Select|Wrap|Line Numbers
  1. Dim con As New OleDb.OleDbConnection
  2.     Dim dbProvider As String
  3.     Dim dbSource As String
  4.     Dim ds As New DataSet
  5.     Dim da As OleDb.OleDbDataAdapter
  6.     Dim sql as string
Then fill the data set (you would need to do this before you access any of the objects I call it in form load.

Expand|Select|Wrap|Line Numbers
  1.     Dim cb As New OleDb.OleDbCommandBuilder(da)
  2.  
  3.         dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
  4.         'dbSource = "Data Source = C:\Users\Kails\Desktop\CrystalDirectoryADD.mdb"
  5.         dbSource = "Data Source = " + Application.StartupPath() + "\DataBase\CrystalDirectoryADD.MDB"
  6.  
  7.         con.ConnectionString = dbProvider & dbSource
  8.  
  9.         con.Open()
  10.  
  11.         Sql = "SELECT * FROM DirectoryADD"
  12.         da = New OleDb.OleDbDataAdapter(Sql, con)
  13.         da.Fill(ds, "CrystalDirectory")
  14.  
  15.         con.Close()
  16.  
Sorry if the code is abit messy, its just copied from one of my old programs. So you have to adapt it to yours.
Feb 27 '11 #6
Right, after making the changes I ran the program I now get this error.
Expand|Select|Wrap|Line Numbers
  1. "A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
  2. System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>MyProgram1.vshost.exe</AppDomain><Exception><ExceptionType>System.Data.OleDb.OleDbException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Not a valid file name.</Message><StackTrace>   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
  3.    at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
  4.    at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
  5.    at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
  6.    at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
  7.    at System.Data.OleDb.OleDbConnection.Open()
  8.    at MyProgram.frmCustomers.btnSave_Click(Object sender, EventArgs e) in E:\Ian Griffiths\MyProgramNEW\MyProgram1\Form1.vb:line 44
  9.    at System.Windows.Forms.Control.OnClick(EventArgs e)
  10.    at System.Windows.Forms.Button.OnClick(EventArgs e)
  11.    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
  12.    at System.Windows.Forms.Control.WmMouseUp(Message&amp;amp; m, MouseButtons button, Int32 clicks)
  13.    at System.Windows.Forms.Control.WndProc(Message&amp;amp; m)
  14.    at System.Windows.Forms.ButtonBase.WndProc(Message&amp;amp; m)
  15.    at System.Windows.Forms.Button.WndProc(Message&amp;amp; m)
  16.    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp;amp; m)
  17.    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;amp; m)
  18.    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  19.    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp;amp; msg)
  20.    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
  21.    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
  22.    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
  23.    at System.Windows.Forms.Application.Run(ApplicationContext context)
  24.    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
  25.    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
  26.    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
  27.    at MyProgram.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
  28.    at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
  29.    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
  30.    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  31.    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  32.    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  33.    at System.Threading.ThreadHelper.ThreadStart()</StackTrace><ExceptionString>System.Data.OleDb.OleDbException: Not a valid file name.
  34.    at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
  35.    at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
  36.    at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
  37.    at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
  38.    at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
  39.    at System.Data.OleDb.OleDbConnection.Open()
  40.    at MyProgram.frmCustomers.btnSave_Click(Object sender, EventArgs e) in E:\Ian Griffiths\MyProgramNEW\MyProgram1\Form1.vb:line 44
  41.    at System.Windows.Forms.Control.OnClick(EventArgs e)
  42.    at System.Windows.Forms.Button.OnClick(EventArgs e)
  43.    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
  44.    at System.Windows.Forms.Control.WmMouseUp(Message&amp;amp; m, MouseButtons button, Int32 clicks)
  45.    at System.Windows.Forms.Control.WndProc(Message&amp;amp; m)
  46.    at System.Windows.Forms.ButtonBase.WndProc(Message&amp;amp; m)
  47.    at System.Windows.Forms.Button.WndProc(Message&amp;amp; m)
  48.    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp;amp; m)
  49.    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;amp; m)
  50.    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  51.    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp;amp; msg)
  52.    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
  53.    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
  54.    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
  55.    at System.Windows.Forms.Application.Run(ApplicationContext context)
  56.    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
  57.    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
  58.    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
  59.    at MyProgram.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
  60.    at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
  61.    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
  62.    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  63.    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  64.    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  65.    at System.Threading.ThreadHelper.ThreadStart()</ExceptionString></Exception></TraceRecord>"
Also I don't understand SQL, I only know very basic skills of Visual Basic as i'm studying it on a Level 3 course in College. So if you could explain to me about the SQL bit as well i'd be much appreciated.

Thanks
Feb 27 '11 #7
The problem may be that the filename you have inserted for your database is not correct. Bare in mind if you are running your app from VB the startup path will be in the bin folder. So for VB testing it is best to give a full app Path(eg C:\database.mdb) The sql command is there to tell the adapter what information to fetch from the table. You could use it to only find dates in a certain range for example. Or only a certain field. In my code it fetches everything.

Here is a fully working form I just put together to explain it to you. You need to create a form(Form1) two text boxes(TextBox1 and TextBox2) and a Button(Button1)

Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.  
  3.     'Global Declarations
  4.     Dim da As OleDb.OleDbDataAdapter
  5.     Dim ds As New DataSet
  6.  
  7.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  8.  
  9.         'Private Declarations
  10.         Dim cb As New OleDb.OleDbCommandBuilder(da)
  11.         Dim con As New OleDb.OleDbConnection
  12.         Dim dbProvider As String
  13.         Dim dbSource As String
  14.         Dim sql As String
  15.  
  16.         dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
  17.         dbSource = "Data Source = C:\DATABASE.mdb" 'The location of your database
  18.  
  19.         con.ConnectionString = dbProvider & dbSource
  20.         con.Open() 'Open the database
  21.  
  22.         'Fetch the data Wanted
  23.         sql = "SELECT * FROM TABLENAME" 'In this case I am selected everything from a table called 'TABLENAME'
  24.         da = New OleDb.OleDbDataAdapter(sql, con)
  25.         da.Fill(ds, "YOURNAME") 'Fill the dataset with the information from your table then nickname it 'YOURNAME'
  26.  
  27.         con.Close()
  28.  
  29.     End Sub
  30.  
  31.  
  32.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  33.  
  34.         'Private Decalrations
  35.         Dim cb As New OleDb.OleDbCommandBuilder(da)
  36.         Dim dsNewRow As DataRow
  37.  
  38.         dsNewRow = ds.Tables("YOURNAME").NewRow() 'Open a new row in the data set
  39.  
  40.         dsNewRow.Item("FIELDNAME1") = TextBox1.Text 'Add the text in textbox1 to FIELDNAME1
  41.         dsNewRow.Item("FIELDNAME2") = TextBox2.Text 'Add the text in textbox2 to FIELDNAME2
  42.  
  43.         ds.Tables("YOURNAME").Rows.Add(dsNewRow) 'Save the new row to the data set
  44.  
  45.         'Update the TABLE with the data set information
  46.         'If this is not done the changes are not saved to the table
  47.         'Changes to the dataset only last until the application is closed
  48.         'Updating the data adapter saves the changes to the table in your database
  49.         da.Update(ds, "YOURNAME")
  50.  
  51.     End Sub
  52.  
  53. End Class
If you copy that code directly and create a Database(C:\DATABASE.MDB) With a Table(TABLENAME) containing two fields(FIELDNAME1, and FIELDNAME2) it will work. then you can get a handle on why it all works and adapt it to your application.
Feb 27 '11 #8
Okay, thanks so much Kalen :) i'll test it then get back to you soon :)
Feb 27 '11 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: aseaman | last post by:
I am a big novice with MySQL and PHP. I need a script that enters information from a html form into a MySQL database. Can anyone tell me where I can find one that I can just replace the table and...
6
by: Max | last post by:
i want to insert a predefined string in a textarea when i right click on the mouse. i need to do it in internet explorer and mozilla.
2
by: Lloyd | last post by:
I am trying to insert text in a text area. I need to insert one set of values on the left side of the text area and have corresponding values on the left side of the text area in an even column....
1
by: Senthil Kumar | last post by:
Hi all, I am opening an image from file or url. I want to insert text and bitmap images on that Image at desired location. Any suggestions please. -- Regards, M.K.Senthil Kumar,
1
by: name | last post by:
Say I have an xml document called test.xml that looks like this: <?xml version="1.0"?> <!--test.xml--> <theroot> <group_a> <stuff>This</stuff> <stuff>is</stuff> <stuff>a</stuff>
0
by: Javier | last post by:
I have a problem when i try to insert text in a word document.I have bookmarks in the word doc but when intesrt text in a determinate range(i use the range property of word bookmarks) i don't get...
6
by: Lelle | last post by:
Hello ! how can i insert text containg code examples from a textbox into a database using SQL insert statment. i have no problem to just add text that dont contains code and script examples...
1
by: Jonathan Smith | last post by:
I have a text file and i need to be able to insert text into it at specified points. How do i do this?
0
by: gazanfar | last post by:
Yes thanks Question is that ---I want to insert image/or image path in my SQlServer 2000 through Visual basic application.like after scan of any photo i want insert in database on whoever's no...
1
by: rahia307 | last post by:
hi to all i want to use Aajx in php and want to insert data into database. but i have no idea about it. if any one have idea for it please help me
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.