Getting Control Properties by Function VB.NET - vb.net

I am trying to create a function that will create some properties for a control (in this case, a combobox). However, the receiving control does not get the value properties from the function.
Here is the function that creates the property.
Public Function getComboboxProperties(ByVal dt As DataTable) As
ComboBox
Try
Dim ctrlCombobox As New ComboBox
ctrlCombobox.BindingContext = New BindingContext
ctrlCombobox.DataSource = dt
ctrlCombobox.ValueMember = "ID"
ctrlCombobox.DisplayMember = "DESCRIPTION"
getComboboxProperties = ctrlCombobox
Catch ex As Exception
Return Nothing
MessageBox.Show(ex.ToString, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try End Function
new value is passed by:
cmbCompanyStatus = clsCommon.getComboboxProperties(dtStatus)
When I open the form, combobox cmbCompanyStatus does not pick up the datasource and displays nothing.
Any help would be greatly appreciated. Thank you!.

Looking at this, you appear to be missing the following:
' Snip
ctrlCombobox.DataSource = dt
ctrlCombobox.ValueMember = "ID"
ctrlCombobox.DisplayMember = "DESCRIPTION"
ctrlCombobox.DataBind() ' <-------------------- This line here
getComboboxProperties = ctrlCombobox

I would suggest the likely cause is an exception being thrown somewhere in your assignments. The statements
Return Nothing
MessageBox.Show(ex.ToString, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
are the wrong way round; the function will return without displaying the message box.
Also,
getComboboxProperties = ctrlCombobox
is a rather old-fashioned way of returning a value; in VB.Net one would prefer
Return ctrlCombobox

Related

Is there a way to retrieve text from a webpage to a TextBox in VB.NET?

Let say I have a TextBox1 and a SaveButton. A website "www.example.com/code1.text" with just a content:
303981
How to retrieve this 303981 to a TextBox?
Do we need a WebBrowser1?
Please help me I'm self learning and beginner also.
Look at the System.Net.WebClient type.
Using wc As New WebClient()
TextBox1.Text = wc.DownloadString("www.example.com/code1.text")
End Using
You need to place a webbrowser control on your form. I would use CefSharp for this
(see: https://www.youtube.com/watch?v=6d-AgfFzr70)
then you can do something like:
settings = New CefSettings
CefSharp.Cef.Initialize(settings)
browser = New ChromiumWebBrowser("www.google.com")
Which loads google.com, just change it to the page you want to load.
Now check your website and see if you can get that textbox value by javascript from the console (F12). Check the source if you can access it with it's ID or that you need to use it's class.
for example:
document.getElementsByClassName('textboxclass')[0].value;
if you manage to get the right value back in your browser console, you can go ahead in your program and do somethinh like:
Dim task As Task(Of JavascriptResponse) = browser.EvaluateScriptAsync(code)
where code contains your javascript.
you may do something like:
task.ContinueWith(
Sub(t)
Try
If t.IsFaulted = False And t.Result IsNot Nothing Then
Dim response = t.Result 'Error: Result is not a member of Task'
If response.Success And response.Result IsNot Nothing Then
taskResult = response.Result
Else
taskResult = "bad result"
End If
End If
Catch ex As Exception
'Dbg("!!!!!!!!!!!!!!! Exception: " & ex.ToString)
taskResult = ex.ToString
End Try
End Sub)
to get the result in a string.

Selecting/Filtering Data from LiteDB in Visual Basic .NET

I'm trying to retrieve data from a LiteDB NOSQL database but i'm struggling to get the syntax correct in Visual Basic.
The database is created correct (validated in LiteDBViewer) and I can count the values in the collection, but when I try to generate the query using collection.Find(), Intellisense puts in query:=, not Query.Operation, as per the documentation.
Try
Using db As LiteDB.LiteDatabase = New LiteDB.LiteDatabase("Sig.db")
Dim brands = db.GetCollection(Of Brand)("Brand")
Dim brands_count As Integer = brands.Count()
If brands_count > 0 Then
'get Brands
Dim brands_results = brands.Find(query:=("Name")) <-- Problem Row
Dim brand_name As String
For Each result In brands_results
brand_name = result.Name.ToString
BrandGrid.Rows.Add(New String() {brand_name, True, True})
Next
End If
End Using
Catch SQLex As LiteDB.LiteException
MessageBox.Show(SQLex.Message, SQLex.ErrorCode.ToString, MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
MessageBox.Show(ex.Message, ex.InnerException.ToString, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I guess I'm struggling with the converting the c# code to VB.net or missing something obvious.
All help or advice appreciated.
Speaking to the developer over Twitter, he suggested using Lambda Expressions.
As a result, the value is as follows:
Dim brands_results = brands.Find(Function(x) x.Name.Equals(SelectedBrand))
(SelectedBrand being a string variable declared earlier)

add image to a Toolstripbutton from image

I have a small issue with my taskbar.The main idea is to create my own taskbar. And I would like to get the application icon to the ToolbarButton
I am using this code
ToolStrip2.Items.Clear()
For Each proc As Process In Process.GetProcesses
Try
ImgList.Images.Add(Icon.ExtractAssociatedIcon(proc.MainModule.FileName))
If proc.MainWindowTitle <> "" Then
Dim menuitem As New ToolStripButton() With
{
.Text = proc.MainWindowTitle,
.Image = ImgList.Images.Count - 1 **//The Error is here**
}
ToolStrip2.Items.Add(menuitem)
End If
Catch ex As Exception
End Try
Next
And I get this error "Value of type 'Integer' cannot be converted to 'Image'"
I know what does it mean, but I dont know how to solve the problem.
Thanks for Help
Use :
ImgList.Images(ImgList.Images.Count - 1)
Remember image of toolstrip must be image not integer!

VB.Net Textbox Input Text as Variable Name

I wanted to test if I could get this to work: I have two textboxes with IDs Textbox1 and Textbox2. I enter the name of a variable I have stored in my program in Textbox1 and then I enter any value in Textbox2. After clicking on a confirm button I want to have the value of the variable name that I've written in Textbox1 changed to the value I wrote in Textbox2.
Something like this (in pseudocode)
GetVariable(Textbox1.Text) = Textbox2.Text
Is there an easy way to get this done or will I be forced to create other type of functions to get around this kind of problem?
Yes, you can do this using reflection.
dim property = this.GetType().GetProperty(Textbox1.Text)
property.SetValue(this, Textbox2.Text)
This will not work on local variable, but it will work on properties.
Of course the better way would be to just use a Dictionary(of string, string) instead of loose variable. Then you can just write myValues(Textbox1.Text) = Textbox2.Text.
Another example of using Reflection. This will work on Fields or Properties. They can be Public or Private, and you don't have to exactly match the Case:
Try
Dim FI As System.Reflection.FieldInfo = Me.GetType.GetField(TextBox1.Text, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(FI) Then
FI.SetValue(Me, TextBox2.Text)
Else
Dim PI As System.Reflection.PropertyInfo = Me.GetType.GetProperty(TextBox1.Text, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(PI) Then
PI.SetValue(Me, TextBox2.Text)
Else
MessageBox.Show(TextBox1.Text, "Field or Property not found!")
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Unable to Set Value")
End Try
Or you can also create a label control at runtime with the value of TextBox1 Text and assign a value according to the Text of TextBox2. This label will be invisible:
Dim MyNewObject As Control
MyNewObject = New Label
MyNewObject.Name = Textbox1.Text
MyNewObject.Text = Textbox2.Text
MyNewObject.Visible = False
Me.Controls.Add(MyNewObject)
And you can use it as a variable in any part of the form. Example to show the value should be as follows:
MsgBox(Me.Controls(Textbox1.Text).Text)

Is it possible to customize error message "Column does not allow nulls" in a datatable?

I have a form with controls bound to a datatable in VB.net.
When keeping empty a field that should be filled, I'm receiving the error message : Column does not allow nulls.
Is it possible to replace this error message string by another one ?
There are a lot of ways when it comes to error handling.
You could get your code to throw a custom error alert:
This will throw an alert with the text: NullCollumContent
Try
'your code here
Catch ex As Exception
Throw New System.Exception("NullCollomContent")
End Try
Also as K3rnel31 explained:
This will just show a simple message box to the user
Try
'your code here
Catch ex As Exception
msgbox("error message here")
End Try
You could also use If statements to check the string:
This if checks the length of the string and checks if its equal to 0:
If Not yourString.Length = 0 Then
'your code here
else
'some error handling here
End If
This if checks if your string is equal to "" which basically means an empty string:
If Not yourString Is "" Then
'your code here
Else
'some error handling here
End If
Try
'your code here to the datatable
Catch ex As Exception
msgbox("changed error string here")
End Try
Thank you all for your answers but that's not really my problem.
Everything is about DataTable Object.
My problem is that I don't know where the exception is raised.
Let me explain.
Assume Column X has AllowDBNull property to false
And I'm not creating manually a new row that I add to the table
Which means I'm not using such code:
Dim NewRow as DataRow = DataTable.NewRow
NewRom.Item("X") = textbox1.text
DataTable.rows.add(NewRow)
If I was using that code, I would have indeed added the Try/Catch
Dim NewRow as DataRow = DataTable.NewRow
NewRom.Item("X") = textbox1.text
try
DataTable.rows.add(NewRow)
catch Ex as Exception
...
end try
I'm using a DataNavigator which adds in a hidden manner the new row to be added to the table.
So, if Column X is empty, he raises by himself the error. It's not an Exception to be handled. It's an error displayed at run time. Programmatically speaking, nothing went wrong at run time. It seems like DataTable object is designed with this feature and default Error Message.
I hope it's clear now.