Dynamically Add UserControl to Form - vb.net

I would like to dynamically add a usercontrol to a form in VB.Net. I will be pulling the UserControl name (String) from a database and if that UserControl exists in the project I would like it to be added to the form.
I know how to programmatically add usercontrols to a form, but I am not sure how when using a string for the name.
Dim userContName As UserControl = dtModules.Rows(k).Item("uc_Name")
Panel1.Controls.Add(userContName)
I attempted this soultion
Public Sub LoadGroups()
dtModules = Tbl_GroupModulesTableAdapter1.GetDataBy_spGetModuleByGroup(grp.Name)
For k = 0 To dtModules.Rows.Count - 1
If grp.Name = dtModules.Rows(k).Item("Module_Group") Then
Dim fullyQualifiedClassName As String = dtModules.Rows(k).Item("Module_Name")
If fullyQualifiedClassName = Nothing Then
Else
Dim o = fetchInstance(fullyQualifiedClassName)
Dim b = CType(o, Control)
grp.Controls.Add(b)
End If
End If
Next
End Sub
Public Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
Dim o As Object = Nothing
Try
For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
If (ay.Name = nspc) Then
o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
Exit For
End If
Next
Catch
End Try
Return o
End Function

Ok got it to work with this;
Dim ucName As String = Projectname.UserControlName
Dim newType As Type = Type.[GetType](ucName, True, True)
Dim o As Object = Activator.CreateInstance(newType)
Form.Controls.Add(o)
Once I got this it was pretty simple! thanks for the feedback!

Related

Setting Values Using Reflection

I am using VB.NET. I have created a small scale test project that works similar to my program. I am trying to say something like: getObjectType(object1) if Object1.getType() = "ThisType" then get the properties. Each object contains an ID and I would like to do this: Object1.Id = -1 (I know it won't be that short or easy). I thought there was a way to do this by using something like: Object1.SetValue(Value2Change, NewValue) but that doesn't work and I'm not sure how to exactly do this. Below is my code. Thank You!
Module Module1
Sub Main()
Dim Db As New Luk_StackUp_ProgramEntities
Dim Obj1 As IEnumerable(Of Stackup) = (From a In Db.Stackups).ToList
Dim Obj2 As IEnumerable(Of Object) = (From a In Db.Stackups).ToList
Dim IdNow As Integer = Obj1(0).IdStackup
Dim StackUpNow As Stackup = (From a In Db.Stackups Where a.IdStackup = IdNow).Single
Console.WriteLine(StackUpNow)
getInfo(StackUpNow)
getInfo(Obj1(0), Obj1(0))
areObjectsSame(Obj1(0), Obj1(67))
switchObjects(Obj1(0), Obj2(1))
getObjectValues(Obj2(55))
Console.WriteLine("========================================")
TestCopyObject(StackUpNow)
ChangeObjectValues(StackUpNow)
Console.ReadKey()
End Sub
Private Sub ChangeObjectValues(Object1 As Object)
Console.WriteLine("Changing Object Values")
Dim myField As PropertyInfo() = Object1.GetType().GetProperties()
'Dim Index As Integer 'Did not find value
'For Index = 0 To myField.Length - 1
' If myField(Index).ToString.Trim = "IdStackup" Then
' Console.WriteLine("Found the ID")
' End If
'Next
If Object1.GetType().Name = "Stackup" Then
'Set the Value
End If
End Sub
You can use PropertyInfo.SetValue to set the value using reflection. You could also use a LINQ SingleOrDefault query to simplify finding the correct PropertyInfo, so you could do something like this:
Private Sub ChangeObjectValues(Object1 As Object)
Console.WriteLine("Changing Object Values")
Dim t As Type = Object1.GetType()
If t.Name = "Stackup" Then
Dim myField As PropertyInfo = t.GetProperties() _
.SingleOrDefault(Function(x) x.Name = "IdStackup")
If myField IsNot Nothing Then
Console.WriteLine("Found the ID")
myField.SetValue(Object1, -1)
End If
End If
End Sub
It's not clear from the question if you really need to use reflection - perhaps a common interface to define the id property, or just type checking and casting, etc. would be better.
Well, I struggled to see how your code example applied to your question, but if you are simply asking how to set the ID of an object using reflection, this code might help you. The trick is that a property is typically handled using a set and a get method.
Imports System.Web.UI.WebControls
Imports System.Reflection
Module Module1
Sub Main()
Dim tb As New Label()
Dim t As Type = tb.GetType()
If TypeOf tb Is Label Then
Dim mi As MethodInfo = t.GetMethod("set_ID")
mi.Invoke(tb, New Object() {"-1"})
End If
Console.WriteLine(tb.ID)
Console.ReadLine()
End Sub
End Module

Trying to populate combobox from SQLite VB.NET Windows Universal App

I am new to SQLite and I am trying to populate a ComboBox in a Windows Universal App from the database. I did the following so far:
With cmbPaciente.Items
Try
Dim sConexao As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "\Banco\Pronto Facil.db")
Dim aConexao As New SQLite.SQLiteConnection(sConexao)
Dim Comando = aConexao.Execute("select Nome from Dados_Pessoais")
For Each item In Comando
.Add(item)
Next
Catch ex As Exception
.Add("Text 1")
.Add("Text 2")
End Try
End With
I am getting this error:
BC32023 Expression is of type 'Integer', which is not a collection type.
I understood thats because aConexao.Execute is returning an integer, but how else should I do it then?
I was using the wrong approach, this way it Works:
With cmbPaciente.Items
Dim sConexao As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Deal.db")
Dim aConexao As New SQLiteConnection(New SQLitePlatformWinRT(), sConexao)
For Each item As Stockvb In aConexao.Table(Of Stockvb)()
Dim newlist As New Stockvb()
newlist.Id = item.Id
newlist.Symbol = item.Symbol
combolist.Add(newlist)
Next
cmbPaciente.ItemsSource = combolist
End With
And here is the Stockvb class:
Public Class Stockvb
<PrimaryKey, AutoIncrement>
Public Property Id() As Integer
Get
Return m_Id
End Get
Set
m_Id = Value
End Set
End Property
Private m_Id As Integer
<MaxLength(8)>
Public Property Symbol() As String
Get
Return m_Symbol
End Get
Set
m_Symbol = Value
End Set
End Property
Private m_Symbol As String
End Class
Special thanks to Grace Feng - MSFT

query an exchange distribution list

I'm trying to find some code that I can use in vb.net 4.0 to query the our exchange 2013 server. It will be housed on a web server and that server does not have outlook installed on it. Looks like I need to use EWS to do this but I've tried a lot of code snippets and still have not been able to figure this out. The distribution list i'm trying to query is in the public folders/Office Contacts. I've tried examples that use nesting to go through the public folder seen there is no deep traversal but I'm not doing something right there. I am not posting code because i'm not sure it would help. I was hoping someone has already done this and would give me some nuggest of info to get me started.
The examples I've found do not query the distribution list but rather add to it. It's not that I haven't tried... I've got hundreds of lines of code from different places that I've tried and tried to learn from.. but i'm not getting it done. Anyway.. help would be great.
Sorry about not posting any code.. I actually thought I deleted this post.. but i'll post the code that is now working for me. This code does a query to the public folder and then grabs some of the data about each contact in that contact list.
Public Sub MS()
Dim oTheListS As New List(Of TheList)
Dim service As New ExchangeService(ExchangeVersion.Exchange2010_SP1)
service.Credentials = New WebCredentials("userid", "password")
service.AutodiscoverUrl("email#address")
'Get Public Folder
Dim sf As SearchFilter = New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Office Contacts")
Dim rrRes As FindFoldersResults = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, sf, New FolderView(1))
Dim OfficeContacts As Folder = rrRes.Folders(0)
'Find the Distribution List
Dim dlSearch As SearchFilter = New SearchFilter.IsEqualTo(ContactGroupSchema.DisplayName, "Merit Board")
Dim ivItemView As New ItemView(1)
Dim fiResults As FindItemsResults(Of Item) = OfficeContacts.FindItems(dlSearch, ivItemView)
If fiResults.Items.Count = 1 Then
'Enumeate Members
Dim cg As ContactGroup = DirectCast(fiResults.Items(0), ContactGroup)
cg.Load()
For Each gm As GroupMember In cg.Members
Dim o As New TheList
o = MS2(gm.AddressInformation.Address)
oTheListS.Add(o)
'Dim o As New TheList
'Dim ncCol As NameResolutionCollection = service.ResolveName(gm.AddressInformation.Address, ResolveNameSearchLocation.ContactsOnly, True)
'With o
' .Name = gm.AddressInformation.Name
' .Email = gm.AddressInformation.Address
'End With
'oTheListS.Add(o)
Next
End If
End Sub
Public Function MS2(pEmail As String) As TheList
Dim o As New TheList
Dim service As New ExchangeService(ExchangeVersion.Exchange2010_SP1)
service.Credentials = New WebCredentials("userid", "password")
service.AutodiscoverUrl("email#address")
Dim sf As SearchFilter = New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Office Contacts")
Dim rrRes As FindFoldersResults = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, sf, New FolderView(1))
Dim OfficeContacts As Folder = rrRes.Folders(0)
'Find the Distribution List
Dim dlSearch As SearchFilter = New SearchFilter.IsEqualTo(ContactSchema.EmailAddress1, pEmail)
Dim ivItemView As New ItemView(1)
Dim fiResults As FindItemsResults(Of Item) = OfficeContacts.FindItems(dlSearch, ivItemView)
If fiResults.Items.Count = 1 Then
Dim con As Contact = fiResults.Items(0)
'Dim ncCol As NameResolutionCollection = service.ResolveName(gm.AddressInformation.Address, ResolveNameSearchLocation.ContactsOnly, True)
With o
If con.DisplayName IsNot Nothing Then
.Name = con.DisplayName
End If
Dim em As New EmailAddress
If con.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, em) = True Then
.Email = con.EmailAddresses(EmailAddressKey.EmailAddress1).ToString
End If
If con.JobTitle IsNot Nothing Then
.Title = con.JobTitle
End If
Dim phy As New PhysicalAddressEntry
If con.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Business, phy) = True Then
.Address = con.PhysicalAddresses(PhysicalAddressKey.Business)
End If
If con.PhoneNumbers.TryGetValue(PhoneNumberKey.BusinessPhone, String.Empty) = True Then
.PhoneBusiness = con.PhoneNumbers(PhoneNumberKey.BusinessPhone)
End If
If con.PhoneNumbers.TryGetValue(PhoneNumberKey.MobilePhone, String.Empty) = True Then
.PhoneMobile = con.PhoneNumbers(PhoneNumberKey.MobilePhone)
End If
If con.CompanyName IsNot Nothing Then
.Comapny = con.CompanyName
End If
End With
End If
Return o
End Function
Public Class TheList
Public Property Name As String
Public Property Email As String
Public Property PhoneMobile As String
Public Property PhoneBusiness As String
Public Property Comapny As String
Public Property Title As String
Public Property Address As PhysicalAddressEntry
End Class
I just got it working so I haven't started to refine it yet.. but hopefully this will help someone else as I didn't find any code that did this

Matlab - Catia connection error

I need to set up live connection between Catia and Matlab so I can send parameters values to my parametric design in Catia and read some other parameters and measures.
This is my sollution:
First I create:
VB NET (*.dll)
Public Class CatiaLinkLibrary
Dim CATIA As Object
Dim rootproduct
Sub StartCatia()
CATIA = CreateObject("CATIA.Application")
End Sub
Sub CloseCatia()
CATIA.Quit()
End Sub
Sub Visible(ByRef mode As Integer)
If mode = 1 Or mode = 0 Then
CATIA.Visible = mode
End If
End Sub
Sub OpenFile(ByRef filename As String)
CATIA.Documents.Open(filename)
rootproduct = CATIA.ActiveDocument.Product()
End Sub
Function GetMass() As Double
Return rootproduct.Analyze.Mass()
End Function
Function GetVolume() As Double
Return rootproduct.Analyze.Volume()
End Function
Function GetArea() As Double
Return rootproduct.Analyze.WetArea()
End Function
Function GetGravityCenter()
Dim gravitycenter(2)
rootproduct.Analyze.GetGravityCenter(gravitycenter)
GetGravityCenter = gravitycenter
End Function
Function GetIntertia()
Dim inertia(8)
rootproduct.Analyze.GetInertia(inertia)
GetIntertia = inertia
End Function
Sub ChangeParameter(ByRef parameterName As String, ByRef Value As Double)
Dim pd As Object
Dim part As Object
Dim parameters As Object
Dim length As Object
pd = CATIA.ActiveDocument
part = pd.Part
parameters = part.Parameters
length = parameters.Item(parameterName)
length.Value = Value
part.Update()
End Sub
Function GetParameter(ByRef parameterName As String) As Double
Dim pd As Object
Dim part As Object
Dim parameters As Object
Dim length As Object
pd = CATIA.ActiveDocument
part = pd.Part
parameters = part.Parameters
length = parameters.Item(parameterName)
Return length.Value()
End Function
Sub closeDoc(ByRef name As String)
Dim windows As Object
Dim window As Object
Dim doc As Object
windows = CATIA.Windows
window = windows.Item(name)
window.Activate()
window.Close()
doc = CATIA.ActiveDocument
doc.Close()
End Sub
Sub activeDoc(ByRef name As String)
Dim windows As Object
Dim window As Object
Dim doc As Object
windows = CATIA.Windows
window = windows.Item(name)
window.Activate()
doc = CATIA.ActiveDocument
End Sub
Function GetArea2() As Double
Dim pd As Object
Dim part As Object
Dim bodys As Object
Dim body As Object
Dim spabench As Object
Dim mymeas As Object
pd = CATIA.ActiveDocument
part = pd.Part
bodys = part.Bodies
body = bodys.Item("PartBody")
spabench = pd.GetWorkbench("SPAWorkbench")
mymeas = spabench.GetMeasurable(body)
Return mymeas.Area
End Function
End Class
Then, in Matlab I have class that wraps around this *dll:
Matlab class:
classdef CatiaLink < handle
properties
catia;
end
methods
function obj = CatiaLink()
%modify this path to your .NET DLL
NET.addAssembly('C:\DOKTORAT\Modele Geometryczne\CatiaLinkLibrary\CatiaLinkLibrary\bin\Debug\CatiaLinkLibrary.dll');
obj.catia = CatiaLinkLibrary.CatiaLinkLibrary;
obj.catia.StartCatia;
disp('Catia started')
end
function Visible(obj,mode)
obj.catia.Visible(mode);
end
function Quit(obj)
obj.catia.CloseCatia;
end
function Open(obj,filename)
obj.catia.OpenFile(filename);
end
function mass = GetMass(obj)
mass = obj.catia.GetMass;
end
function vol = GetVolume(obj)
vol = obj.catia.GetVolume;
end
function area = GetArea(obj)
area = obj.catia.GetArea;
end
function cog = GetCenterOfGravity(obj)
tmp = obj.catia.GetGravityCenter;
cog = [tmp(1),tmp(2),tmp(3)];
end
function inertia = GetInertia(obj)
tmp = obj.catia.GetIntertia;
inertia = [tmp(1), tmp(2), tmp(3); ...
tmp(4), tmp(5), tmp(6); ...
tmp(7), tmp(8), tmp(9)];
end
function setParameter(obj, parameterName, Value)
obj.catia.ChangeParameter(parameterName, Value);
end
function val = getParameter(obj, parameterName)
val = obj.catia.GetParameter(parameterName);
end
function closeDoc(obj, name)
obj.catia.closeDoc(name);
end
function activeDoc(obj, name)
obj.catia.activeDoc(name);
end
function area = getArea2(obj)
area = obj.catia.GetArea2;
end
end
end
So in my program I create Catia object by Catia = CatiaLink.
And than I use it like 10000 or even more times to set and get parameters.
Everything works just fine up to around couple thousand times and than I get error:
Error using CatiaLink/setParameter (line 42)
Message: No more threads can be created in the system. (Exception from
HRESULT: 0x800700A4)
Source: mscorlib
HelpLink:
Can someone explain what is happening? And how to prevent this?
It looks like you're never calling Catia.Quit()

Referencing an Unbound DataGridView Without Specifically Naming It?

I am using 3 unbound DataGridView controls to display certain information. To load the information into those DGVs, I am pulling the information from an encrypted file, decrypting it, parsing the information, then trying to fill the DGVs with that information. The loading from the file is called by the menu item click. Here is what I have so far:
Private Sub miCLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles miCLoad.Click
Dim FilePath As String = "C:\FList\CList.clt"
Dim LoadFile As New SaveandLoad.SaveAndLoad
Dim FileRead As New Simple3Des("MyPassword")
Dim FileString As String = FileRead.ReadFile(FilePath)
With LoadFile
.WhichList = dgCourses
.FilePath = FilePath
.DecryptedString = FileRead.DecryptData(FileString)
.dgList = dgCourses
End With
Call LoadFile.LoadFile()
End Sub
Public Class SaveandLoad
Public Property WhichList As New DataGridView
Public Property FilePath As String
Public Property DecryptedString As String
Public Property EncryptedString As String
Public Property dgList As Control
Public Sub LoadFile()
Dim dgRow As DataGridViewRow
Dim dgCell As DataGridViewTextBoxCell
Dim Lines() As String = DecryptedString.Split(vbLf)
Dim LinesList As List(Of String) = Lines.ToList
LinesList.RemoveAt(Lines.Length - 1)
For Each Line As String In LinesList
Dim Fields() As String = Line.Split(",")
dgRow = New DataGridViewRow
For x = 0 To (WhichList.Columns.Count - 1) Step 1
dgCell = New DataGridViewTextBoxCell
dgCell.Value = Fields(x).ToString
dgRow.Cells.Add(dgCell)
Next
WhichList.Rows.Add(dgRow)
Next
Select Case WhichList.Name
Case "dgCourses"
frmFacultyList.dgCourses = WhichList
frmFacultyList.dgCourses.Refresh()
WhichList.Dispose()
Case "dgFList"
frmFacultyList.dgFList = WhichList
frmFacultyList.dgFList.Refresh()
WhichList.Dispose()
Case "dgSList"
frmFacultyList.dgSList = WhichList
frmFacultyList.dgSList.Refresh()
WhichList.Dispose()
End Select
MsgBox("List Successfully Loaded", vbOKOnly, "Load")
End Sub
I want to be able to reference (or fill) a DGV without using 'select case' or 'if-then' statements. This will be too inefficient once I start adding the many other DGVs, that will be added in the future. Therefore, the title is the main question. I am using VS Express 2010.
I don't know VB too much, however, I'll post my solution in C# (may be helpfull in some way....)
DataGridView myDGV;
foreach (var item in this.Controls)
{
if (item.GetType() == typeof(DataGridView))
{
if (((DataGridView)item).Name == WhichList.Name)
{
//Cannot assing to 'item' here, because it is a 'foreach iteration variable'
//However you can save the variable for later use.
myDGV = (DataGridView)item;
}
}
}
myDGV = WhichList;
// different approach
DataGridView myDGV = (DataGridView)this.Controls.Find(WhichList.Name, false).First();
myDGV = WhichList;
Here is what worked for me in VB.NET:
Dim FormControls As New frmFacultyList.ControlCollection(frmFacultyList)
For Each DGV As DataGridView In FormControls
If WhichList.Name = DGV.Name Then
DGV = WhichList
DGV.Refresh()
End If
Next
Make an instance of the control collection then search specifically for DGVs using For Each. Simple and efficient.