Dynamically creating a dropdown, with values from SQL server - sql-server

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.

Related

Crystal Report not showing data from SQL Server 17.5

After creating a table and putting data in it in the previous form, this form tries to display the report, but I am getting a blank report. What am I doing wrong?
Here is my VB 2017 code for form load event:
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form5
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cryRpt As New ReportDocument
cryRpt.Load("C:\Users\Administrator\source\repos\WindowsApp3\WindowsApp3\CrystalReport4.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class
I solved my problem in the following way
Here is my modified VB 2017 code for form load event:
Dim query As String = "SELECT * FROM monAtt"
Dim cmd As New SqlCommand(query, conn1)
cmd.CommandType = CommandType.Text
conn1.Open()
Dim MyDA As New SqlClient.SqlDataAdapter()
MyDA.SelectCommand = cmd
Dim myDS As New TestDataSet1()
MyDA.Fill(myDS, "monAtt")
Dim oRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument()
oRpt.Load("C:\Users\Administrator\source\repos\WindowsApp3\WindowsApp3\CrystalReport4.rpt")
oRpt.SetDataSource(myDS.Tables("monAtt"))
CrystalReportViewer1.ReportSource = oRpt
CrystalReportViewer1.RefreshReport()
CrystalReportViewer1.Visible = True
conn1.Close()
cmd.Dispose()

How to display data from SQL Server on a DataGridView

I want to load or show the data from SQL Server on a DataGridView.
The build succeeds and there's no error when I run it. There's nothing wrong in form modul_koneksi (I think) because it works on my other form (form_login)
However, nothing shows up in my DataGridView. How can I fix this?
Code:
Imports System.Data.SqlClient
Public Class FormProduk
Private Sub FormProduk_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
Dim connection As New SqlConnection(str)
Dim com As String = "Select * From tbl_user"
Dim dataadapter As New SqlDataAdapter(com, connection)
Dim dataset As New DataSet()
dataadapter.Fill(dataset, "tbl_user")
DataGridView1.DataSource = dataset.Tables()
End Sub
End Class
You should define which table to load in the DataGridView:
DataGridView1.DataSource = dataset.Tables("tbl_user")
You cannot set the .DataSource property with dataset.Tables. Instead you need to set it with a DataTable located in your DataSet:
DataGridView1.DataSource = dataset.Tables("tbl_user")
However I think you could simplify the code a little by getting rid of the SqlDataAdapter and loading straight into a DataTable
Dim dt As New DataTable
dt.Load(com.ExecuteReader())
DataGridView1.DataSource = dt
I would also consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
With the changes your code would look something like this:
Dim dt As New DataTable
Using con As New SqlConnection("Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"),
cmd As New SqlCommand("SELECT * FROM tbl_user", con)
con.Open()
dt.Load(cmd.ExecuteReader())
End Using
DataGridView1.DataSource = dt
Not enough info to tell, are you sure your connection string str is correct. You can try change to this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "Data Source=Fahriy;Initial Catalog=DBLogin;Integrated Security=True"
Dim conn As New SqlConnection(str)
Dim cmd As String = "Select * From tbl_user"
Dim adapter As New SqlDataAdapter(cmd, conn)
Dim tabeluser As New DataSet
adapter.Fill(tabeluser)
DataGridView1.DataSource = tabeluser.Tables
End Sub

delete record from database in listview in vb

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

Unable to display SQL database data on Visual basic form

I am facing a problem displaying the records of my table on the visual basic form I have created.
This is my code :
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
myconnection = New SqlConnection("server=HOME-PC\SQLEXPRESS;uid=sa;pwd=123;database=college")
myconnection.Open()
mycommand = New SqlCommand("SELECT * from demo3)", myconnection)
Dim mySqlDataAdapter As New SqlDataAdapter(mycommand)
Dim mydsStudent As New DataSet()
mySqlDataAdapter.Fill(mydsStudent, "Student")
ra = mycommand.ExecuteNonQuery()
MessageBox.Show("Data Displayed" & ra)
myconnection.Close()
End Sub
End Class
Note: my database name is "college" , table name is "demo3" . Table contains 2 columns namely name and roll no. How to display the data in those columns on the visual basic form that I have created ?
You don't need to call execute non query. You can bind the dataset to a DataGridView. Like this
Dim DataGridView1 as new DataGridView()
DataGridView1.DataSource = mydsStudent
'Your table goes here, not sure about the exact propety name, hope it works.
DataGridView1.DisplayMember = "demo3"
Me.Controls.Add(DataGridView1)

Loading data from SQL Server row by row to textboxes

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);

Resources