vb.net - adding a picture box programmatically to a tablelayoutpanel - vb.net

morning all,
i'm programmatically pulling rows from a db and listing them in my vb.net app like so...
Dim linkurl As String = ""
Dim linkdescription As String = ""
Dim adapter As MySqlDataAdapter
Dim hyperlinkresultstable As DataTable
cn.ConnectionString = connection_string
Dim commandtext As String
commandtext = "Select * from mytable where username = '" & "' and type='HYPERLINK';"
adapter = New MySqlDataAdapter(commandtext, cn)
hyperlinkresultstable = New DataTable
adapter.Fill(hyperlinkresultstable)
For Each row As DataRow In hyperlinkresultstable.Rows
linkurl = row.Item("value")
linkdescription = row.Item("description")
quicklinks_layout.RowStyles.Add(New RowStyle(SizeType.AutoSize))
quicklinks_layout.RowCount += 1
quicklinks_layout.Controls.Add(New PictureBox(), 0, quicklinks_layout.RowCount - 1)
quicklinks_layout.Controls.Add(New LinkLabel(), 1, quicklinks_layout.RowCount - 1)
Next row
I've never worked in this way before and I've not got a single idea on how to set the 'image' property of the Picturebox added.
I also need to be able to set the text value, tooltip value and mouseclick event of the linklabel based on the current row's linkurl and link description aswell.
Any advice or direction is appreciated! Thanks as always!! :)

Related

Can't display Data in ComboBox Control of DropDownStyle (DropDownList)

I have the following requirement,
I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database Table, and it's working fine.
(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.
(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.
Am I missing something here or is it like that? Any advice will be highly appreciated.
Im filling it in runtime using a procedure.
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
cmbDisProfile.DataSource = tempTb
cmbDisProfile.DisplayMember = "discount_profile"
End Sub
Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.
My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.
Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)
Return fetchedDataTable
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)
Dim SqlCmd As New SqlCommand(sqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
dataAdapter.Update(tbToUpdate)
End Sub
Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
Try
Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"
'Dim searchString As String = txtCategoryCode.Text
' searchOwnerCmd.Parameters.Clear()
' searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(searchSql)
If tempTb.Rows.Count = 0 Then
Return False
Else
Return True
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)
Return fetchedSearchTB
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].
How do you fill/populate your ComboBox with Data From Database Table ?
In this link, Microsoft docs state, that:
Use the SelectedIndex property to programmatically determine the index
of the item selected by the user from the DropDownList control. The
index can then be used to retrieve the selected item from the Items
collection of the control.
In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.
proposed,
ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"
does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
Dim i As Integer = 0
For i = 0 To tempTb.Rows.Count - 1
cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
Next
End Sub
After adding we can use the following code to display the data on combobox (DropDownList).
Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
Try
Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
If Len(txtItCode.Text) < 4 Then
cmdAdd.Enabled = False
cmdDelete.Enabled = False
cmdSave.Enabled = False
Else
If tempTb.Rows.Count > 0 Then
With tempTb
txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
End With
cmdAdd.Enabled = False
cmdDelete.Enabled = True
cmdSave.Enabled = True
Else
cmdAdd.Enabled = True
cmdDelete.Enabled = False
cmdSave.Enabled = False
txtItName.Text = ""
Call fillItCategories()
Call fillProProfile()
Call filldisProfiles()
Call fillFinCat()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

How to get value from second column from a combobox which is linked to SQL DB

I have build a WindowForm application that has a combobox which has a Data Binding Mode to a View on SQL Database and textbox.
The View query: "SELECT [CompanyName],CountryName FROM [CompanyRefTable]"
The members of the combobox are as follow:
DataSource: CDALLENTITIESLISTBindingSource
DisplayMember:CompanyName
ValueMember: CompanyName
SelectedValue: CompanyName
I have done some modifications to the code (updated on page)
Now Im getting the values from the second column:)
My code:
Dim rowView As DataRowView = TryCast(Me.cmbEntity.SelectedItem, DataRowView)
If (Not rowView Is Nothing) Then
Dim row As DataRow = rowView.Row
Dim subjectName As String = DirectCast(row.Item("CountryName"), String)
Me.txtCountry.Text = subjectName.ToString
End If
Thank you for your help!
Thank you to :jmcilhinney for your comment it helped me in finding solution:)
I found an solution for my issue on internet:
Dim rowView As DataRowView = TryCast(Me.cmbEntity.SelectedItem, DataRowView)
If (Not rowView Is Nothing) Then
Dim row As DataRow = rowView.Row
Dim subjectName As String = DirectCast(row.Item("CountryName"), String)
Me.txtCountry.Text = subjectName.ToString
End If

connecting datatable with datagrid asp.net

so i was trying to bind my datagrid to a datatable and i came up with this code
now everything seems to be working but it does not shows nothing on my gridview it doesnt even shows the datagrid at all when i execute anyone know what is the problem because i cant figure it out everything should be working fine but the gridview does not load .
Dim mrDB As New Odbc.OdbcConnection(myDAC.OBDC)
Dim dgrMR As New DataTable
Dim dr As DataRow
dgrMR.Columns.Add("Data")
dgrMR.Columns.Add("Utente")
dgrMR.Columns.Add("Nome")
dgrMR.Columns.Add("Série")
dgrMR.Columns.Add("Tipo")
dgrMR.Columns.Add("Estado")
dgvMarcacoes.Columns.Clear()
Dim sqlStr As String = "select distinct data,idno,idnome, u_tratam as serie, u_tipomr, Max(estado) as estado " &
"from [marca].[mr]"
sqlStr += queryFilter
sqlStr += "group by idno,idnome, u_tratam, data, u_tipomr "
'this msgbox shows a correct string (that works on sql) so the problem is not on this part
'MsgBox(sqlStr, MsgBoxStyle.OkOnly, "controlo")
mrDB.Open()
Dim mrComm As New Odbc.OdbcCommand(sqlStr, mrDB)
Dim mrReader = mrComm.ExecuteReader
Dim b = New StringBuilder()
If Not (mrReader.HasRows) Then
Me.dgvMarcacoes.Visible = False
MsgBox("Não há marcações para o dia indicado", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "ATENÇÃO...")
Else
'Me.dgvMarcacoes.Visible = True
While mrReader.Read
dr = dgrMR.NewRow()
dr(0) = Trim(mrReader(0))
dr(1) = Trim(mrReader(1))
dr(2) = Trim(mrReader(2))
dr(3) = Trim(mrReader(3))
dr(4) = Trim(mrReader(4))
dr(5) = Trim(mrReader(5))
dgrMR.Rows.Add(dr)
'dr.Item(5).Value = Trim(estado(mrReader(5)))
End While
End If
dgvMarcacoes.DataSource = dgrMR
dgvMarcacoes.DataBind()
mrDB.Close()
'so i tried this to see if the data was passing correctly to my datatable and it is :\
For i = 0 To dgrMR.Rows.Count - 1
For u = 0 To dgrMR.Columns.Count - 1
MsgBox(dgrMR.Rows(i)(u).ToString)
Next
Next
You have a tag as asp.net but you have MsgBox in your code indicating that is a WinForm application. Check if the grid columns are AutogenerateColumns=True and change it to false

letting user type and add value to an already bound combobox

I have one combobox in my app that gets populated with a dozen or so items from SQL SERVER. I am currently trying to allow user to be able to type in a new value into the combobox and save it to a table in SQL SERVER. I'm looking for something along the lines of a DropDownStyle of DropDown and DropDownList. Basically I'm hoping to let the user type in the combobox, however if the value is not there, i want to be able to give them an option of saving it (probably on lost focus). I'm wondering what would be a good way of doing something like that.
On lost focus should I basically go through each item that is currently in the drop down and check it against the value entered?
EDIT:
Sql="SELECT IDvalue, TextName from TblReference"
Dim objconn As New SqlConnection
objconn = New SqlConnection(conn)
objconn.Open()
Dim da As New SqlDataAdapter(sql, objconn)
Dim ds As New DataSet
da.Fill(ds, "Name")
If ds.Tables("Name").Rows.Count > 0 Then
Dim dr As DataRow = ds.Tables("Name ").NewRow
ds.Tables("Name").Rows.InsertAt(dr, 0)
With c
.DataSource = ds.Tables("Name")
.ValueMember = " IDvalue "
.DisplayMember = " TextName "
End With
End If
You are already adding a fake/blank row to a table, you can do the same thing for a new item.
' form level datatable var
Private cboeDT As DataTable
Initializing:
cboeDT = New DataTable
Dim sql = "SELECT Id, Descr FROM TABLENAME ORDER BY Descr"
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(sql, dbcon)
dbcon.Open()
cboeDT.Load(cmd.ExecuteReader())
' probably always need this even
' when there are no table rows (???)
Dim dr = cboeDT.NewRow
dr("Id") = -1 ' need a way to identify it
dr("Descr") = ""
cboeDT.Rows.InsertAt(dr, 0)
End Using
End Using
cboeDT.DefaultView.Sort = "Descr ASC"
cboE.DataSource = cboeDT
cboE.DisplayMember = "Descr"
cboE.ValueMember = "Id"
Note Users tend to have a preference as to the order of these things. The simple creatures tend to prefer alphabetical over a DB Id they may never see. To accommodate them, the DefaultView is sorted so that any new rows added will display in the correct order.
Add new items in the Leave event (much like Steve's):
Private Sub cboE_Leave(sender ...
' if it is new, there will be no value
If cboE.SelectedValue Is Nothing Then
' alternatively, search for the text:
'Dim item = cboeDT.AsEnumerable().
' FirstOrDefault(Function(q) String.Compare(q.Field(Of String)("Descr"),
' cboE.Text, True) = 0)
'If item Is Nothing Then
' ' its new...
Dim newid = AddNewItem(cboE.Text)
Dim dr = cboeDT.NewRow
dr("Id") = newid
dr("Descr") = cboE.Text
cboeDT.Rows.Add(dr)
' fiddling with the DS looses the selection,
' put it back
cboE.SelectedValue = newid
End If
End Sub
If you want to search by text:
Dim item = cboeDT.AsEnumerable().
FirstOrDefault(Function(q) String.Compare(q.Field(Of String)("Descr"),
cboE.Text, True) = 0)
If item Is Nothing Then
' its new...
...
Inserting will vary a little depending on the actual db. A key step though is to capture and return the ID of the new item since it is needed for the CBO:
Private Function AddNewItem(newItem As String) As Int32
Dim sql = "INSERT INTO MY_TABLE (Descr) VALUES (#v); SELECT LAST_INSERT_ID();"
Dim newId = -1
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(sql, dbcon)
dbcon.Open()
cmd.Parameters.Add("#v", MySqlDbType.String).Value = newItem
' MySql provides it in the command object
If cmd.ExecuteNonQuery() = 1 Then
newId = Convert.ToInt32(cmd.LastInsertedId)
End If
End Using
End Using
Return newId
End Function
As noted MySql provides the LastInsertedID as a command object property. In SQL SERVER, tack ...";SELECT LAST_INSERT_ID();" to the end of your SQL and then:
newId = Convert.ToInt32(cmd.ExecuteScalar())
This is not conceptually very different from Steve's answer, except it uses the DataTable you build rather than collections which makes it (very) slightly simpler.
The way I do this, is on window load I perform a new SQL query to get the list of values in the table, and load them into a combobox.
Then once focus is lost, it then checks what's currently typed into the combobox against the current values already loaded. If it doesn't exist, then it's not in SQL. Something like the following...
Dim found As Boolean = False
For i As Integer = 0 To comboBox.Items.Count - 1
Dim value As String = comboBox.Items(i).ToString()
If comboBox.Text = value Then
found = True
End If
Next
If found = False Then
'the item doesn't exist.. add it to SQL
Else
'the item exists.. no need to touch SQL
End If
First thing I would do is to build a simple class to hold your values through a List of this class
Public Class DataItem
Public Property IDValue As Integer
Public Property TextName as String
End Class
Now, instead of building an SqlDataAdapter and fill a dataset, work with an SqlDataReader and build a List(Of DataItem)
' Class global...
Dim allItems = new List(Of DataItem)()
Sql="SELECT IDvalue, TextName from TblReference"
' Using to avoid leaks on disposable objects
Using objconn As New SqlConnection(conn)
Using cmd As New SqlCommand(Sql, objconn)
objconn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read()
Dim item = new DataItem() With { .IDValue = reader.GetInt32(0), .TextName = reader.GetString(1)}
allItems.Add(item)
End While
End Using
if allItems.Count > 0 Then
allItems.Insert(0, new DataItem() With {.IDValue = -1, .TextValue = ""}
Dim bs = new BindingList(Of DataItem)(allItems)
c.DataSource = bs
c.ValueMember = "IDvalue"
c.DisplayMember = "TextName"
End If
End Using
End Using
Now the code that you want to add to your Leave event for the combobox
Sub c_Leave(sender As Object, e As EventArgs) Handles c.Leave
If Not String.IsNullOrEmpty(c.Text) Then
Dim bs = DirectCast(c.DataSource, BindingList(Of DataItem))
if bs.FirstOrDefault(Function(x) x.TextName = c.Text) Is Nothing Then
Dim item = new DataItem() With { .IDValue = -1, .TextName = c.Text}
bs.Add(item)
' here add the code to insert in the database
End If
End If
End Sub

vb.net - button.text not aligning when pulled from data table

Please refer to the images below:
So the left image has a hardcoded string and the image on the right has the data pulled in form an MSSQL database.
The code below makes up these buttons (they are dynamically created based on the amount of records in the database table)
'Button
Private Sub LoadUseraccount()
'Connect to Database (from module1)
connectSQL()
'Setup DataAdapter with query
Dim da As SqlDataAdapter
da = New SqlDataAdapter("SELECT * from useraccounts", SQLConn)
'Store results in temporary datatable
Dim dt As DataTable
dt = New DataTable()
da.Fill(dt)
Dim i As Integer
'Create a button for every record shown in useraccount table.
For i = 0 To dt.Rows.Count - 1
Dim dr As DataRow = dt.Rows(i)
Dim newbutton As New Windows.Forms.Button
Dim dataString As String = CStr(dr.Item("username"))
newbutton.Name = "btnButton" & i
newbutton.Text = dataString '<========= This Line is where the button text is set
newbutton.Top = 200 + i * 105
newbutton.Left = 40
newbutton.TextAlign = ContentAlignment.MiddleCenter
newbutton.Height = 107
newbutton.Width = 180
Dim myFont As System.Drawing.Font
myFont = New System.Drawing.Font("Arial", 20.25)
newbutton.Font = myFont
newbutton.ForeColor = Color.White
newbutton.BackColor = Color.MidnightBlue
Me.Controls.Add(newbutton)
Next
SQLConn.Close()
End Sub
So the only difference in the images is what the text is set to display on the buttons, but the alignment is all out of whack when the string is not static.
What am I doing wrong or what am I missing to have the right image formatted the same as the left one?
Cheers :-)
I have tried your example and I was unable to reproduce the problem until I added a carriagereturn/linefeed to the variable used for button text.
So I assume that your data contains some unprintable characters that disalign your output.
A simple fix should be
newbutton.Text = dataString.Trim()