How do I add htmltablecell data to database after I click submit - vb.net

I created an htmltable in .aspx.vb, because I have a lot of rows that come from database and they depend on the querystring. that part is fine. But when someone makes a change in one of the cells how do I save data back to database?
Code -
Dim tr As New HtmlTableRow
Dim td As New HtmlTableCell
td = New HtmlTableCell
Dim txtbox1 As New TextBox
txtbox1.ID = "price_" & rd("id")
txtbox1.Text = rd("price")
td.Controls.Add(txtbox1)
tr.Cells.Add(td)
tb1.Rows.Add(tr)
Now when someone changes the price in the textbox, how do I save it in database?
This is code for submit button -
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
Dim sqlcnn As SqlConnection = Nothing, sqlstr As String = "", sqlcmd As SqlCommand
sqlstr = "UPDATE ???"
sqlcmd = New SqlCommand(sqlstr, sqlcnn)
sqlcmd.ExecuteScalar()
End Sub
Please answer in detail.

I would suggest using the built in grid controls. Here is a walkthrough Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
. It might be better to start with Walkthrough: Basic Data Access in Web Pages.
If you choose to move forward with HTML then here is one way to do it based on what you provided. You can add an update button and try this code in that event:
'Create an update Command with the apropriate paramaters'
Dim sql = ("UPDATE SO_Prices SET Price = #Price WHERE ID = #ID")
Dim Cmd As New SqlCommand(sql, connection)
Cmd.Parameters.Add("#Price", SqlDbType.SmallMoney)
Cmd.Parameters.Add("#ID", SqlDbType.Int)
connection.Open()
'Loop through the fields returned'
For Each Key As String In Request.Form.Keys
'Make sure you only process fields you want'
If Key.StartsWith("price") Then
'Pull the ID out of the field name by splitting on the underscore'
' then choosing the second item in the array'
Dim ID As String = Key.Split("_")(1)
'Update the paramaters for the update query'
Cmd.Parameters("#ID").Value = ID
Cmd.Parameters("#Price").Value = Request.Form(Key)
'Run the SQL to update the record'
Cmd.ExecuteNonQuery()
End If
Next
connection.Close()
Let me know if you need any additional assitance. If not, please mark this as the correct answer.

Related

In VB.Net, how to repopulate a datagrid from scratch?

I have written a generic VB.net subroutine that populates a datagrid with the results of a query. The subroutine as one parameter, strQuery, which is a string that can translate to any valid SQL-Server view or stored procedure that returns a recordset. Other than that, there is no constraint on the SQL code, and sending two queries that have entirely different field profiles is a valid proposition.
In order to get this to work, I must completely purge the data grid of whatever dataset had been there previously, thus allowing the control to drop its prior identity and start over, allowing, from scratch, the new dateset to redefine the control's contents.
I have finally solved the problem. Perhaps I should have mentioned that I am using Visual Studio 2010, and that if Hersey were using a later version, then the code that worked for him may not have worked for me. The change to my code is one additional line: setting both the name and datapropertyname to the same name. I noticed that when I went to look at the column view, I noticed that the datapropertyname is how the table links to the source, and the name is an effective alias for the field, how it will be presented. Obviously, for clarity sake, both must be the same! This now works as advertised.
Thanks, ~ Peter Ferber
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("<Enter Connection string here>")
Dim rcd As ADODB.Recordset = ReturnRecordset("Select * From ExcludeWords")
Call DefineDataGrid("Select * From ExcludeWords")
End Sub
Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdate.Click
Call DefineDataGrid("Select * From FindWords")
End Sub
Sub DefineDataGrid(ByVal strQuery As String)
Dim con As New SqlConnection("<Enter Connection String Here>")
Dim dt As New DataTable
FindWordGrid.Columns.Clear()
FindWordGrid.DataSource = Nothing
Dim rcd As ADODB.Recordset = ReturnRecordset(strQuery)
Dim MyField As ADODB.Field
Dim iCount As Integer = -1
FindWordGrid.ColumnCount = rcd.Fields.Count
For Each MyField In rcd.Fields
iCount = iCount + 1
FindWordGrid.Columns(iCount).Name = MyField.Name
FindWordGrid.Columns(iCount).DataPropertyName = MyField.Name
Next
Dim cmd As New SqlCommand(strQuery, con)
Dim da = New SqlDataAdapter(cmd)
da.Fill(dt)
FindWordGrid.DataSource = dt
End Sub
Function ReturnRecordset(strQuery As String) As ADODB.Recordset
Dim con As ADODB.Connection = "<Enter Connection string here>"
ReturnRecordset = New ADODB.Recordset
ReturnRecordset.Open(strQuery, con)
End Function
My setup is easy to reproduce: I am using datasets with only a handful of records in each respective table. The only constraint is that the respective runs must have a different field profile. I have been experimenting with different techniques for much of the day, and I now think it best to get some new grey matter on the subject. Getting this process correctly is the last major hurdle for me, in making a key presentation I wish to make, in lobbying for a job role. Thanks, in advance, for your comments, thoughts, and ideas.
Sincerely, ~ Peter Ferber
So, made a couple modifications to the DefineDataGrid code you've posted. Seems to be working for me. I suspect might be something to do with the life cycle of either your cmd or con objects causing your problem. Parsing a number of different number of queries through to it and it rebuilds the datagridview correctly
Sub DefineDataGrid(ByVal strQuery As String)
Dim dt As New DataTable
FindWordGrid.DataSource = Nothing
Using con As New SqlConnection("Your Connection String Here")
Using cmd As New SqlCommand(strQuery, con)
Dim da = New SqlDataAdapter(cmd)
da.Fill(dt)
FindWordGrid.DataSource = dt
End Using
End Using
End Sub
Changed the obvious module level implementations of con and cmd to local variables, and since both types implement IDisposable, wrapped them in a Using pattern

Add datagrid columns to database?

I'm trying to add a users selected row to the database
I want the CarID, CarBrand, And CarModel to enter
When the user selected that row they click a button to add it to the database
I seem to be getting errors and I'm not sure why
Here is my code
Private Sub Btn_addtorental_Click(sender As Object, e As EventArgs) Handles Btn_addtorental.Click
If datcarsearchresults.SelectedRows.Count = 1 Then
Dim SelectedCarID As Integer = datcarsearchresults.SelectedRows(0).Tag
Dim SelectedCarBrand As String = datcarsearchresults.SelectedColumns(1)
Dim SelectedCarModel As String = datcarsearchresults.SelectedColumns(2)
PublicCarID = SelectedCarID
If DbConnect() Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Insert into Tbl_Rental (CarID,CarBrand,CarModel) " & "Values (#CarID,#CarBrand,#CarModel)"
.Parameters.AddWithValue("#CarID", SelectedCarID)
.Parameters.AddWithValue("#CarBrand", SelectedCarBrand)
.Parameters.AddWithValue("#CarModel", SelectedCarModel)
.ExecuteNonQuery()
It says it cannot be converted to string??
Any help would be appreciated thanks
Where is it erroring? I'm guessing when you try to get the value from the column. The SelectedColumns(1) doesn't bring back a string but brings back a DataGridViewColumnCollection. Take a look at this link with more answers. vb.net how to get cell value from datagridview.

Update grid from a query

I have a Visual Basic 2010 application that uses a DataGridView to display a list of frequencies from a Microsoft Access 2010 database. The application uses the BindingNavigationPostionItem to allow navigation though the table.
The Move Next and Move Previous buttons move you up and down the list. The cool thing is, as you do this, I have code that sends the Frequency and Mode to my Yeasu radio and the radio then is set to that freq/mode.
This works great but, if I try to filter the DataGridView by the Service field, the ID field becomes blank and navigation does not work.
Here is the code that runs after you select what you want to filter by and you click the filter button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmbox1 As String
cmbox1 = ComboBox1.Text
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from HFUtil where service = '" & cmbox1 & "'", MyConn) '
da.Fill(ds, "HFUtil")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
BindingNavigator1.BindingSource = source1
DataGridView1.Refresh()
BindingNavigator1.Refresh()
'=========================================================
ListBox1.Items.Clear()
ListBox1.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ListBox1.Items.Add(sItemTemp)
Next
ComboBox2.Items.Clear()
ComboBox2.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ComboBox2.Items.Add(sItemTemp)
Next
End Sub
The only difference between this code and the code that runs on form load is - where clause in the data adapter.
What am I doing wrong?
I don't see in your code where you apply your filter. So, lets pretend for a second that you load your whole table into DataSet. Then next thing, you either use DataSet.DefaultView or create your custom DataView and assign this to DataSource property - you did this.
Now, all you have to do is apply row filter to the data view you use
view.RowFilter = "service = '" & cmbox1 & "'"
At this point you should only see subset of records and nothing should happen to your Id field. Because your data doesn't change.
I have suspicion, you changing your view somewhere and this is why you have problems.

How to save many pictures from SQL Server database to specific folder using vb.net

I'm new to vb.net and I have a problem to do my task.. Firstly, I have a project in vb.net that has a process button which, when clicked, will show a list of staff names from a SQL Server database (I'm using SQL Server 2008 R2) to a list view. Then I have copy button, one button is for copying the list name to notepad (success) and another one is for copying the list name to Excel (success). The list view includes staff id, first name and last name and each id has its own image (staff image).
I want to save all the images (1137 images) from the SQL Server database to a specific folder on the desktop. I did, but only one image is saved. How can I save all 1137 images to the folder? Can someone help me?
This is my code:
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Dim cn As SqlConnection
cn = New SqlConnection
cn.ConnectionString = "MyConnString;"
Dim cmd As New System.Data.SqlClient.SqlCommand("SELECT pt_image FROM BadgeImages.dbo.portrait")
cmd.Connection = cn
cmd.CommandType = CommandType.Text
cn.Open()
Dim ImgStream As New IO.MemoryStream(CType(cmd.ExecuteScalar(), Byte()))
Dim Image As System.Drawing.Image = System.Drawing.Image.FromStream(ImgStream)
Image.Save("C:\Documents and Settings\prymax\Desktop\images + ".jpg", Imaging.ImageFormat.Jpeg)
End Sub
This code only saves 1 image =(
Public Sub ExportImages()
ConnDB()
sql = "select Photo,ID from student"
cmd = New MySqlCommand(sql, con)
dr = cmd.ExecuteReader
While dr.Read
Dim byteImg As Byte() = CType(dr(0), Byte())
Dim strPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\StudentPics\" & "" & dr(1) & ".jpg"
Dim fs As FileStream = New FileStream(strPath, FileMode.CreateNew, FileAccess.Write)
fs.Write(byteImg, 0, byteImg.Length)
fs.Flush()
fs.Close()
End While
dr.Close()
con.Close()
End Sub
This For me is Working fine
You need to use a DataReader. The following are your options:
use a DataReader, and loop through your results while saving them using the technique you demonstrated above.
turn the contents of btnsave_Click into a function, and loop through a list while passing the data to the said function (using the contents of the list as the identifier for WHERE in your SQL)
you can set each image using DataReader into a Picturebox, then immediately save the content of your Picturebox using
Picturebox.Image.Save("path of image", imagefiletype)
These should all work.

Database not updating new row

Insert new row inside DataGridView
This answer makes it seem like the database should update with the rows.add
Some other sites have instructions, but form a perspective of creating the database from scratch. I already have a database and just want the stupid thing to accept new data.
Here's what I have done:
Private Sub InitializeDataGridView()
Try
' Set up the DataGridView.
With Me.DataGridView1
' Automatically generate the DataGridView columns.
.AutoGenerateColumns = True
' Set up the data source.
'bindingSource1.DataSource = GetData("SELECT * FROM Places and Stuff")
MyTable = GetData("SELECT * FROM Places and Stuff")
'MyDataSet = bindingSource1.DataSource
'MyTable = MyDataSet.Tables(0)
.DataSource = MyTable
' Automatically resize the visible rows.
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
' Set the DataGridView control's border.
.BorderStyle = BorderStyle.Fixed3D
' Put the cells in edit mode when user enters them.
.EditMode = DataGridViewEditMode.EditOnEnter
' Disables Add New Row
.AllowUserToAddRows = False
End With
Catch ex As SqlException
MessageBox.Show(ex.ToString, _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
System.Threading.Thread.CurrentThread.Abort()
End Try
End Sub
I am binding the DGV to a table. It seems like maybe I need a dataset somewhere to update but I cannot figure out how to populate a dataset with a table that is also a sql database. You can also see where I have played around with other datasets/datatables etc.
I also got my datagridview to add a row but the database is being lazy:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Determine Last Row Index
Dim dgvrowCnt As Integer = DataGridView1.Rows.Count - 1
If DataGridView1.Rows.Count > 0 Then
Dim myRow As DataRow = MyTable.NewRow
myRow(0) = DataGridView1.Rows(dgvrowCnt).Cells(0).Value + 1
MyTable.Rows.Add(myRow)
Else
Dim myRow As DataRow = MyTable.NewRow
myRow(0) = 230
MyTable.Rows.Add(myRow)
End If
End Sub
I am a little saddened by not being able to use myRow("<column name here>") = 230 but I'll have to get over it I guess.
I have tried refreshing and checking the table to see if my form needs to be refreshed, but that doesn't seem to be the case.
This page http://support.microsoft.com/kb/301248 has 2 lines and claims it does what I am hoping for:
Dim objCommandBuilder As New SwlCammandBuilder(daAuthors)
daAuthors.Update(dsPubs, "Authors")
I cannot get my table into a dataset as shown in the binding lines of my example.
It seems that you haven't understood a fundamental concept of ADO.NET. The DataTable and other objects like the DataSet are 'disconnected' objects, meaning that adding/updating and removing rows doesn't update/insert/delete the database table.
You need to create an SqlCommand, prepare its command text and then Execute a query to update your db (other methods include using an SqlDataAdapter and its Update method)
For example, to insert a single row in a datatable your code should be something like this
Using con = New SqlConnection(.....constringhere...)
Using cmd = new SqlCommand("INSERT INTO table1 (field1) values (#valueForField)", con)
con.Open()
cmd.Parameters.AddWithValue("#valueForField", newValue)
cmd.ExecuteNonQuery()
End Using
End Using
A more complete tutorial could be found here
Instead this could be a pseudocode to use a SqlDataAdapter and a SqlCommandBuilder to automate the construction of the commands required to store your changes back to the database
' Keep the dataset and the adapter at the global class level'
Dim da As SqlDataAdapter = Nothing
Dim ds As DataSet
Private Function GetData(ByVal sqlCommand As String) As DataSet
ds As New DataSet()
Dim connectionString As String = "Data Source=...."
Using con = New SqlConnection(connectionString)
conn.Open()
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(ds)
End Using
End Using
End Using
Return ds
End Function
Use the first table inside the DataSet returned by GetData as Datasource of the grid (or just use the whole dataset)
.DataSource = GetData(.......).Tables(0)
' Add a new button to submit changes back to the database'
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim builder = New SqlCommandBuilder(da)
da.UpdateCommand = builder.GetUpdateCommand()
da.InsertCommand = builder.GetInsertCommand()
da.DeleteCommand = builder.GetDeleteCommand()
da.Update(ds)
End Sub
Please, note that I cannot test this code, and I offer it as a pseudocode without any error checking required by a more robust application.