I am trying to retrieve data row by row from my SQL Server and load them into my respective textboxes, I was doing the below code but of course it doesn't work as the For Each loop will load every single textboxes with each data retrieved, ran out of ideas. Appreciate if someone can give me a boost here. Thanks.
Private Sub retrieve_Data()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=HPEnvy-HP; Initial Catalog=Cinema; User Id=<id>; Password=<password>;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT [movie_ID], [movie_Title] FROM [Movie_Table] ORDER BY [MOVIE_ID] "
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim reader As String = lrd(1).ToString
Dim arrLoad As New ArrayList
arrLoad.Add(lrd(1).ToString)
For i = 0 To arrLoad.Count - 1
For Each cCtrl As Control In Panel1.Controls
If TypeOf cCtrl Is TextBox Then
Dim txtBox As New TextBox
txtBox = cCtrl
txtBox.Text = arrLoad.Item(i)
End If
Next
Next
End While
Catch ex As Exception
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
End Sub
you just "new" your textbox,
you didn't add your textbox to your form.
you should add some code like that:
this.Controls.Add(textbox);
or
this.Panel1.Controls.Add(textbox);
Related
Hye... I currently doing my final year project using vb.net and i got this error. Im tryin' to fix the error but still not succeed. I use ms access for database in my project. I try to put con.Open() before the 'dt' statement and con.Close() after the 'cboProduct.Select' but the result is the same. Really appreciate your helps. Thanks :)
'GLOBAL DECLARATIONS
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Acer User\Documents\MAKLUMAT IVENTORI.accdb"
Dim con As OleDbConnection = New OleDbConnection(conString)
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim ds As New DataSet
Private Sub RefreshData()
dt = New DataTable
ds = New DataSet
ds.Tables.Add(dt)
adapter = New OleDbDataAdapter("Select * FROM product WHERE lab_kod='66'", con)
adapter.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
labelID.Text = getAutoID()
lblLabCode.Text = "66"
cboProduct.Select()
Dim v_SQL As String = "SELECT * FROM kategori_product"
cmd = New OleDbCommand(v_SQL, con)
con.Open()
Dim v_dataReader As OleDbDataReader = cmd.ExecuteReader()
Dim v_dataTable As New DataTable
v_dataTable.Columns.Add("product_kod", Type.GetType("System.String"))
If v_dataReader.HasRows Then
While v_dataReader.Read
v_dataTable.Rows.Add(v_dataReader.GetString(0))
End While
cboProduct.DataSource = v_dataTable
End If
cboProduct.DisplayMember = "product_kod"
cboProduct.ValueMember = "product_kod"
v_dataReader.Close()
con.Close()
End Sub
Don't store short-lived objects, such as database connections, as global variables.
In fact, don't use global variables, ever, at all.
(though I note that assuming this is a Class and not a Module those are actually class fields, not globals, but you're still misusing them)
Your OleDbDataAdapter.Fill call requires the connection to be open, but you call .Fill(dt) before calling con.Open()
Use Using (using() in C#) blocks to ensure your database connection is always closed, even in the event of failure.
I would like to know how is your way on pulling data from SQL Server to a combobox. I've been trying various solutions but I couldn't make them work.
I've been using this code in my Login form
Private Sub SQLConnect_Click(sender As Object, e As EventArgs) Handles SQLConnect.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Server=" + SQLServer.Text + ";Database=PriceOrders;User Id=" + SQLUser.Text + ";Password=" + SQLPwd.Text + ";"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
MsgBox("Successfully connected!", vbInformation)
cnn.Close()
Hide()
frmMain.Show()
Catch ex As Exception
MsgBox("Invalid Login! Please try again.", vbExclamation)
SQLUser.Text = ""
SQLPwd.Text = ""
SQLUser.Focus()
End Try
End Sub
Will this connection be imported to other form? Because I have my combo box on the other form from this login form.
Thanks guys.
I want to create a feature within my program that when i load in an excel file, it counts how many columns in the spreadsheet and dynamically creates a dropdown for each and every column, to select what header it should be, and bind it to the GridView .Data from SQL server will populate the dropdowns. Some problems i have run into is, how do i have a button where it asks for the file location? i have tried this way to load in a hardcoded location, but it doesnt work.
Sub SubmitBtn_Excel(Sender As Object, E As EventArgs)
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "C:\\spreadsheet.xlsx"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
GridView1.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
End Try
End Sub
I also have a method to call on the database with the table i have created to populate the data, should i put this method all in one method with the excel call?? considering that the dropdown id was dynamically created, it doesnt know how to find it because its not id'd in the HTML
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Page.IsPostBack Then
FillDeptDropdownList()
End If
End Sub
Protected Sub FillDeptDropdownList()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDbCon").ConnectionString)
Dim cmd As New SqlCommand("Select * from demofeepay.dbo.catagories", con)
Dim adp As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
adp.Fill(dt)
ddlDynamic.DataSource = dt
ddlDynamic.DataTextField = "catagory"
ddlDynamic.DataValueField = "ID"
ddlDynamic.DataBind()
ddlDynamic.Items.Insert(0, "Select Catagory")
End Sub
This is the method i have for creating the dropdown
Sub SubmitBtn_Excel(Sender As Object, E As EventArgs)
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "C:\\Users\\John\\Documents\\John\\EPP\\WorldNet_Notes\\CHRISTIAN_BROTHERS_HIGH_SCHOOL.xlsx"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
GridView1.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
End Try
End Sub
This is the HTML
<form id="form1" runat="server" style="overflow-x:hidden; width:100%">
<div>
<asp:button id="butOK" text="Add Dropdowns" onclick="SubmitBtn_Click" runat="server"/>
<asp:button id="BtnAddExcel" text="Add Spreadsheet" OnClick="SubmitBtn_Excel" runat="server"/>
</div>
<div id ="ddlDynamic">
<!-- Dynamic Dropdowns -->
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
I am aware that this is all over the place, as you can see im a bit lost. I dont really want anybody to spoon fed me the answer, im just unsure how to structure it, or could anybody point me in the right direction to find out more. New to vb. Thanks in advance :-)
First you will need to add a PlaceHolder control to your WebForm.
You will add your DropDownLists to this PlaceHolder this way:
foreach (var item in collection)
{
DropDownList ddl = new DropDownList();
lb.Items.AddRange(item.values);
ddl.ID = "ddl" + (PlaceHolder1.Controls.Count() + 1);
PlaceHolder1.Controls.Add(ddl);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
For your file button, you may want to use the FileUpload control.
I have a problem. In the properties of listview which is checkboxes = "True". Using this checkbox, I want to delete the data in listview and in the database.
Below is the code:
If MessageBox.Show("Do you really want to DELETE this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation cancel", MsgBoxStyle.Information, "Information")
End If
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
Using con = New SqlConnection(dbSource)
Using cmd = New SqlCommand(sql, con)
con.Open()
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
cmd.Parameters.AddWithValue("#code", ColumnRoomCode.Text)
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
Using above code, only the data in listview is deleted. The data in the database not deleted.
The interface for listviewitem:
Thank you if you all can help me. :)
A Command should be executed to have any effect on the database. You need to add this
cmd.ExecuteNonQuery()
in every loop.
Also the connection could be opened just before entering the loop and should be closed afterward. (Using Statement is recommended here)
Said that, please take a look on Parameterized queries because your code is open to Sql Injections and parsing problems. Also the sql command to delete a record doesn't need a list of fields after the FROM table part.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
' Parameterized query
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
' Using statement to ensure proper closing and disposing
' of the objects SqlConnection and SqlCommand
using con = New SqlConnection(dbSource)
using cmd = New SqlCommand(sql, con)
con.Open()
' Add a parameter just one time before the loop with an empty string
cmd.Parameters.AddWithValue("#code", "")
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
' Set the parameter value with the value extracted from the ListViewItem
Dim RoomCode = lvItem.Text
cmd.Parameters("#code").Value = RoomCode
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
End Sub
One last note. The ColumnRoomCode textbox (?) is always the same, so calling delete one time is enough, but I suppose that this should be changed with some value extrated by you current ListViewItem
Join Date: Dec 10
Posts: 10
caba11 is an unknown quantity at this point (<10)
how to save binary file to database
hi.
i need to save files into database...
i cant find why it is not working...
this is my code:
Public Sub importfiles(ByVal sFileName As String)
Dim cnSQL As SqlConnection
Dim cmSQL As SqlCommand
Dim strSQL
'Validate form values
'Read file into a stream
Dim fs As New FileStream(sFileName, FileMode.Open, FileAccess.Read)
Dim myData(fs.Length) As Byte
fs.Read(myData, 0, fs.Length)
fs.Close()
Try
'Build SQL
strSQL = "insert into data_cesta(ID, cesta) values (#ID, #cesta)"
cnSQL = New SqlConnection("Data Source=.;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True")
cmSQL = New SqlCommand(strSQL, cnSQL)
cmSQL.Parameters.Add(New SqlParameter("#ID", SqlDbType.Int)).Value = ID
cmSQL.Parameters.Add(New SqlParameter("#cesta", SqlDbType.NText)).Value = myData
' cmd2.Parameters.Add("#ID", SqlDbType.Int).Value = ID
' cmd2.Parameters.Add("#cesta", SqlDbType.NText).Value = myData
'Open connection and execute the command
cnSQL.Open()
cmSQL.ExecuteNonQuery()
'Close and clean up objects
cnSQL.Close()
cmSQL.Dispose()
cnSQL.Dispose()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
without try it says "cmSQL.ExecuteNonQuery()"-"Failed to convert parameter value from a DataGridViewTextBoxColumn to a Int32."
It looks as though you are loading some file paths into a DataGrid before having them processed into your database.
By default, your ID field is being passed to the procedure as the DataGridViewTextBoxColumn object within the DataGrid. You need to retrieve the text within that object.
You can do so by accessing the associated DataGridViewTextBoxCell object on the row being processed. Within the DataGridViewTextBoxCell object is a property called "Value" which will have the ID value you need.
Without seeing more code, it's hard to give you the exact code, but check out the DataGridViewCell object for some helpful code, since the TextBoxCell inherits from this class.