How to access values from textbox in tablelayoutpanel in vb.net - database

I have created a screen for editing database records. After user selects the table, I have dynamically added Labels and TextBox inside the TableLayoutPanel1. I want to know how to access the value present in the TextBox which is inside TableLayoutPanel1
I code which i used:
Dim strSQL, strSQL1 As String
Dim ln As Integer
Dim reader As OleDbDataReader
Dim connection As OleDbConnection
Dim ds As New DataSet
connection = New OleDbConnection(CONNECT_STRING)
connection.Open()
ln = 0
strSQL = " select * from syscat.columns where TABSCHEMA like 'QA1MM%' and TABNAME like 'SKU_STR_LIST' with ur "
RichTextBox1.Text = RichTextBox1.Text + strSQL
Dim selectCMD As OleDbCommand = New OleDbCommand(strSQL, connection)
reader = selectCMD.ExecuteReader
MessageBox.Show("Column: " & reader(0) & " ")
While reader.Read()
If String.IsNullOrEmpty(reader(0)) Then
Else
TableLayoutPanel1.ColumnCount = 2
TableLayoutPanel1.RowCount = 20
Dim aLabel As New System.Windows.Forms.Label
Dim aTextBox As New System.Windows.Forms.TextBox
aLabel.Name = "New Label"
aLabel.Text = reader(0).Text
TableLayoutPanel1.Controls.Add(aLabel, 0, ln)
TableLayoutPanel1.Controls.Add(aTextBox, 1, ln)
ln = ln + 1
End If
End While
How can i access the value present in the aTextBox which i added dynamically inside the TableLayoutPanel1?

First off you need to set a name on the TextBox. Basically aTextbox.Name = "TextBox1". Then you should be able to find the control by using:
Control c = TableLayoutPanel1.Controls.Find("TextBox1",true)
Keep in mind however that this will give you a control, not a textbox. So typecast it in whatever way you find suitable.
Ctype(c,TextBox)
DirectCast(c,TextBox)

As WozzeC says you need to give the text box a name that is unique, probably something like
aTextBox.Name = "TextBox" & ln
Then you could find it this way
Dim words = TableLayoutPanel1.Controls("Textbox1").Text
or if its in the same loop
Dim words = TableLayoutPanel1.Controls("Textbox" & ln).Text

Related

All Listview data show in textbox using loop

Dim Mysqlconn = New SqlConnection
Mysqlconn.ConnectionString = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Dim dt As DataTable = New DataTable("studentdata")
Mysqlconn.Open()
Dim query As String
query = "select ID from studentdata where Class='" & ComboBox1.Text & "'"
Dim Command = New SqlCommand(query, Mysqlconn)
Dim dr = Command.ExecuteReader(CommandBehavior.CloseConnection)
ListView1.Items.Clear()
Dim x As ListViewItem
Do While dr.Read = True
x = New ListViewItem(dr("ID").ToString)
ListView1.Items.Add(x)
Loop
For i = 0 To ListView1.Items.Count - 1
TextBox1.Text = ListView1.Items(i).SubItems(0).Text
Next
In this code, Textbox1 is showing the last row from Listview1. My requirement is all the Listview1 data show in textbox1 one after one from Listview1. Is this possible to show in textbox1 read all data from Listview1 using loop. Thank you...
A textbox only holds one string at a time. If it's set to allow multiline strings (not clear in the question) you can separate each item with a linebreak. Otherwise you can separate the strings using a delimiter like a comma.
Dim query As String = "select ID from studentdata where Class= #class"
Using conn As New SqlConnection("Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"), _
cmd As New SqlCommand(query, conn)
cmd.Parameters.Add("#class", SqlDbType.NVarChar, 20).Value = ComboBox1.Text
conn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
ListView1.Items.Add(New ListViewItems(dr("ID").ToString()))
End While
End Using
End Using
TextBox1.Text = String.Join(",", ListView1.Items.Select(Function(i) i.SubItems(0).Text))
Also note how I used a query parameter to include the combobox value in the SQL command. That's a big deal; anything else will give you trouble, usually sooner than later.
Using as loop, the proper way would be like so:
Dim lines As New List(Of String)
For i = 0 To ListView1.Items.Count - 1
lines.Add(ListView1.Items(i).Text)
Next
TextBox1.Lines = lines.ToArray()
You can't keep setting the Text property to a new value and expect the old value to hang around for no reason. You could append to the Text each time, but that is inefficient. The proper way is to create a list of the values, convert that to a String array and then assign that to the Lines property.
Note that there is no point getting the Text of the first subitem because that is the same as the Text of the item.

Saving all items from 2 listboxes to a SQL Server database

I am trying to take all the items from a list box and save them into separated fields into a SQL Server database. The user pushes a save button and I would like for all of the items in the list box to be separated into their appropriate fields and saved into said fields in the SQL Server database. The items start out separated in a DGVgrid and are combined when the enter the List box. What is the best way to go about this? The SQL Server database has the same columns and the DGVgrid.
I am using VB in Visual Studio and a SQL Server database that I have created on my machine. Any help would be greatly appreciated. I have been stuck on this for a bit and I'm not sure where to go from here.
I think that the problem may be the List boxes because I have been able to save to my SQL Server database when the data comes from Text boxes, but I do not want to get rid of the List boxes. I have tried changes the List boxes out with DGVgridview boxes, but this did not work. I could not get the items to neatly go into the columns that they needed to. Would I be better of just trying to save the data into a Text file?
Public Function InStrRev(StringCheck As String, StringMatch As String, Optional Start As Integer = -1, Optional Compare As CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary) As Integer
End Function
Public Function InStr(Start As Integer, String1 As String, String2 As String, Optional Compare As CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary) As Integer
End Function
Public Function Mid(Str As String, Start As Integer, Length As Integer) As String
End Function
Static IntStart As Integer
Dim Backpack1 = BP1ListBox.ToString()
Dim Backpack2 = BP2ListBox.ToString()
Dim user As String = ReturningUser.UserNametxt.Text
Dim con As SqlConnection
Dim deletecmd As SqlCommand
Dim objcmd As SqlCommand
Dim deletereader As SqlDataReader
Dim reader As SqlDataReader
Dim BackpackName As String
Dim item As String
Dim weightposition As Integer
Dim weight As String
Dim username As String = CStr(ReturningUser.UserNametxt.Text)
Dim delete As String = "Delete From UserBackpackItems where UserName = '" & username & "'"
Dim stmt As String = "Insert Into UserBackpackItems(UserName, BackpackName, Item, Weight,) Values('" & username & "', '" & BackpackName & "', '" & ItemNametxt.Text & "', '" & ItemWeighttxt.Text & "')"
con = New SqlConnection("Data Source=DESKTOP-AUS1VBC\SQLEXPRESS;Initial Catalog=BackpackDatabase;Integrated Security=True")
con.Open()
'delete previous save
deletecmd = New SqlCommand(delete, con)
deletereader = deletecmd.ExecuteReader()
'create a new save
For Counter = IntStart To BP1ListBox.Items.Count - 1
Dim ListItems As String = BP1ListBox.Items.ToString
item = Mid(ListItems(Counter), 1, InStr(1, ListItems(Counter), " ", CompareMethod.Text))
weightposition = InStrRev(ListItems(Counter), " ", CompareMethod.Text)
weight = Mid(ListItems(Counter), weightposition, Length:=BP1ListBox.Items(Counter))
objcmd = New System.Data.SqlClient.SqlCommand(stmt, con)
reader = objcmd.ExecuteReader()
Next

Graph Not Drawing Values vb.net

dtTest.Columns.Add("TestName", GetType(String))
dtTest.Columns.Add("Score", GetType(Integer))
Dim cn As New OleDbConnection(connectionString)
cn.Open()
Dim cmd As New OleDbCommand("SELECT * From ScoreDB WHERE StudentName='" & SelectStudent.Text & "'", cn)
cmd.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
Dim TestName As String = Convert.ToString(reader("TestName"))
Dim TestScore As String = Convert.ToString(reader("ScorePercentage"))
GraphValues.Add(TestName, TestScore)
End While
Dim point As KeyValuePair(Of String, Integer)
For Each point In GraphValues
dtTest.Rows.Add(point.Key)
dtTest.Rows.Add(point.Value)
MsgBox(point.Key)
Next
With Chart1.ChartAreas(0)
.AxisX.Minimum = 0
.AxisX.Maximum = 10
.AxisY.Minimum = 0
.AxisY.Maximum = 100
.AxisY.Interval = 10
.AxisX.Title = "Test"
.AxisY.Title = "Score Percentage"
End With
cn.Close()
End Sub
I've created a form that should output a the score and test name into a column chart in vb.net, It loads all the data from the database successfully but it fails to write it to the graph and ends up just like this
any help would be appreciated as I am really struggling with this at the moment and have searched various resources such as MSDN.
Nothing is telling the chart to map the datatable GraphValues to the chart. Try something like below. You may to tinker around with the code slightly
Chart1.DataSource = GraphValues
Chart1.Series(0).XValueMember = "TestName"
Chart1.Series(0).YValueMembers = "Score"
'Data bind to the selected data source
Chart1.DataBind()
http://blogs.msdn.com/b/alexgor/archive/2009/02/21/data-binding-ms-chart-control.aspx

Row data into string conversion vb.net 2010

How can I convert a row data into string or text and display it into a label? My problem is when I click on my login button which contains the SQL code that gains a row data into alabel, the result in my label is false. not the text. How can I convert it into string?
Here's my code:
Private Sub cmdLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLog.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
Dim reader As MySqlDataReader = Nothing
Dim sapi
sapi = CreateObject("sapi.spvoice")
connection.ConnectionString = ("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Calupad\Desktop\HTF feat Yiyet\HTF feat Yiyet\Database1.mdf;Integrated Security=True;User Instance=True")
command.CommandText = "SELECT * FROM [Users] WHERE Username='" & txtUser.Text & "' AND Password ='" & txtPass.Text & "';"
txtWel.Text = "Welcome Back, " + txtUser.Text + "!....."
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(dataset, "0")
txtStat.text = command.CommandText = "SELECT Status FROM [Users] WHERE Username = '" & txtUser.Text & "' ".ToString
txtStat.Text = stat
Dim count = dataset.Tables(0).Rows.Count
If count > 0 Then
MsgBox("Login Successful!" & vbNewLine & txtStat.Text, MsgBoxStyle.Information, "Access Granted")
sapi.speak(txtWel.Text)
Me.Hide()
Form1.Show()
frmMenu.Show()
txtUser.Clear()
txtPass.Clear()
tries = 3
Else
ctr = tries - 1
tries = ctr
sapi.speak(txtUser.Text + txtNot.Text)
MsgBox("Invalid Account!" + vbNewLine + "Attempts Remaining: " & tries, vbCritical, "Access Denied")
txtUser.Clear()
txtPass.Clear()
If tries = 0 Then
MsgBox("You've reached the maximum attempts!" + vbNewLine + "The program will be terminated.", vbCritical, "Terminated!")
Me.Close()
End If
End If
End Sub
First of all, the way you check for username and password is weak and is most certainly volnurable to SQL injections. You are checking if the 'count' of rows is greater than zero then the user has logged in successfully, where as you should only compare count to 1. and instead of counting the rows, try to compare the row values to what the user has input in the username and passoword fields and what is returned from the database rows.
The "hacker" can simply type this and he will be allowed to log in according to the logic of your code:
You just need to retrieve the data stored into dataset variable that you filled using the adapter.
Assuming your database table contains fields like First_Name and 'Last_Name', here is how you can display them on any label control on your form:
adaptor.Fill(dataset, "0")
myFirstName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
myLastName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
You can also retrieve the column without having to know its name like this
myLabel.text = = dataset.Tables(0).Rows(0).Item(3).ToString()
'This will retrieve the 4th column from the table (zero based array)
You can also clean up your code by declaring a variable to hold the retrieved table
adaptor.Fill(dataset, "0")
Dim myTable as DataTable = dataset.Tables(0)
myFirstName.Text = myTable.Rows(0).Item(0).ToString()
Hope this helps

DataTimePicker for ListView

Is there a way to use DateTimePicker as your searching device for ListView?
I don't know how to use DateTimePicker as my search engine...
HERE IS THE CODES FOR MY SEARCH:
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
ListView1.Items.Clear()
conn = New SqlConnection("Data Source=#####;Initial Catalog=#####;Persist Security Info=True;User ID=#####;Password=#####")
Dim strQ As String = String.Empty
strQ = "SELECT ControlNo,EmpNo,CheckOutDate,CheckOutTime,TaxiNo,PlateNo,Model,Make FROM dbo.ChkInOut WHERE ControlNo ='" + txtsearch.Text + "'"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
There are few problems with your code as is, so let's take them one at a time
SqlCommand inherits from DbCommand, which implements the IDisposable interface.
The primary use of this interface is to release unmanaged resources.
The best way do that is with the Using keyword. For a code example of that, take a look at the sample code at the bottom of this page.
Same goes for SqlConnection, wrap it in a Using statement.
Don't concatenate strings together to make SQL queries, this opens your application up to SQL Injection attacks. There are examples of how to create parameterized queries here and here (unfortunately I didn't see a good example on MSDN).
In your case, the query will look like this:
strQ = "SELECT ControlNo, ..<rest of columns>.. ,Model,Make " & _
"FROM dbo.ChkInOut " & _
"WHERE ControlNo = #controlNo"
cmd = New SqlCommand(strQ, conn)
cmd.Parameters.AddWidthValue("#controlNo", txtsearch.Text);
... rest of code here ...
To query by a user specified date, you need to first get the date from the DateTimePicker.Value property. Then construct a query (like in the example above) and pass a parameter with the selected date. You may find this question abou SQL Server dates helpful.

Resources