vb.net use string as a previously created object instance - vb.net

Not sure exactly what I need to do to make this work, so my description may be lacking at first. Essentially I am writing a program launcher that recreates itself each time on load. It pulls the data regarding the tabs and buttons from an SQLite database and builds itself dynamically at run time. I get my problem when I pass the tab name through to the function that creates the buttons. I need the name to pull the right set of buttons from the database and I then tried to use the name to place the buttons on the right tab when I create them, but the debugger calls it a null reference because it doesn't point correctly to the tabpage that I'm trying to make it point to (at least that is what I'm guessing). Any ideas on how to make this work right?
Private Sub CreateTabs()
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLiteCommand
SQLconnect.ConnectionString = "Data Source=" & sPath & "\dock.db;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT title FROM tabs"
Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
Dim Tabs(25) As String
Dim c As Integer = 1
While SQLreader.Read()
Tabs(c) = SQLreader(0)
c = c + 1
End While
SQLcommand.Dispose()
SQLconnect.Close()
For i = 1 To UBound(Tabs)
If Tabs(i) <> "" Then
Launcher.TabPages.Add(Tabs(i))
CreateButtons(Tabs(i))
End If
Next
End Sub
Private Sub CreateButtons(ByVal tab)
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLiteCommand
SQLconnect.ConnectionString = "Data Source=" & sPath & "\dock.db;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT id,name,path FROM buttons WHERE tab = '" & tab & "'"
Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
While SQLreader.Read()
For i = 1 To 9
Dim NewButton(i) As Button
If Not SQLreader(2) Is System.DBNull.Value Then
Dim myIcon As System.Drawing.Icon = Icon.ExtractAssociatedIcon(SQLreader(2))
End If
Dim toolTip1 As ToolTip = New System.Windows.Forms.ToolTip(Me.components)
Me.Controls(tab).tabpages.add(NewButton(i)) '<--this causes my problem
'NewButton(i).Width = 32
'NewButton(i).Height = 32
'NewButton(i).Text = i
'NewButton(i).Image = myIcon.ToBitmap
'If Not SQLreader(1) Is System.DBNull.Value Then
'toolTip1.SetToolTip(NewButton(i), SQLreader(1))
'toolTip1.Active = True
'End If
Next
End While
SQLcommand.Dispose()
SQLconnect.Close()
End Sub

I think you've got two problems here:
You're trying to find the tab control by the tab name. You should instead find the tab control itself (or pass it in) and find the name of the tab inside that control. Otherwise you're trying to add a button to a collection of tab pages, instead of to a specific tab.
You're never actually creating a new button. You're creating an array of buttons for every iteration of the loop, but not a new actual Button object. Admittedly that doesn't jibe with your suspicion that it's due to tab pages, but it's certainly a problem...
I suspect you want this as your loop (where tabControl is the TabControl passed in):
While SQLreader.Read()
For i = 1 To 9
If Not SQLreader(2) Is System.DBNull.Value Then
Dim myIcon As Icon = Icon.ExtractAssociatedIcon(SQLreader(2))
End If
Dim toolTip1 As ToolTip = New ToolTip(Me.components)
Dim NewButton As Button = New Button
NewButton.Width = 32
NewButton.Height = 32
NewButton.Text = i
NewButton.Image = myIcon.ToBitmap
tabControl.TabPages(tab).Controls.Add(NewButton)
If Not SQLreader(1) Is System.DBNull.Value Then
toolTip1.SetToolTip(NewButton, SQLreader(1))
toolTip1.Active = True
End If
Next
End While
Hopefully that's right - my VB.NET isn't great...
I'm surprised your original code compiled though - do you have Option Strict on?
You should also use a Using statement for your command and connection so they get disposed even when an exception occurs.

Thanks for the help, but I found my answer. Apparently I just needed to reference the index of the tab like so:
Private Sub CreateTabs()
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLiteCommand
SQLconnect.ConnectionString = "Data Source=" & sPath & "\dock.db;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT title FROM tabs"
Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
Dim Tabs(25) As String
Dim c As Integer = 1
While SQLreader.Read()
Tabs(c) = SQLreader(0)
c = c + 1
End While
SQLcommand.Dispose()
SQLconnect.Close()
For i = 1 To UBound(Tabs)
If Tabs(i) <> "" Then
Launcher.TabPages.Add(Tabs(i))
CreateButtons(Tabs(i), i - 1)
End If
Next
End Sub
Private Sub CreateButtons(ByVal tab, ByVal TabIndex)
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLiteCommand
SQLconnect.ConnectionString = "Data Source=" & sPath & "\dock.db;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT id,name,path FROM buttons WHERE tab = '" & tab & "'"
Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
While SQLreader.Read()
For i = 1 To 9
Dim NewButton As New Button
Launcher.TabPages.Item(TabIndex).Controls.add(NewButton)
NewButton.Width = 32
NewButton.Height = 32
NewButton.Location = New Point(10 + (SQLreader(0) * 32) + 10, 10)
NewButton.Text = SQLreader(0)
If Not SQLreader(2) Is System.DBNull.Value Then
Dim toolTip1 As ToolTip = New System.Windows.Forms.ToolTip(Me.components)
Dim myIcon As System.Drawing.Icon = Icon.ExtractAssociatedIcon(SQLreader(2))
NewButton.Image = myIcon.ToBitmap
toolTip1.SetToolTip(NewButton, SQLreader(1))
toolTip1.Active = True
End If
Next
End While
SQLcommand.Dispose()
SQLconnect.Close()
End Sub

Related

i copy and paste my code from another form but when it reaches 10 it stops counting only print more 10

Instead of counting 1,2,3,4,5...infinity it counts like this 1,2,3,4,5,6,7,8,9,10,10,10,10,10,10...
I don't see what's wrong and it does not have any error.
Private Sub GenID()
If sql.cnn.State = ConnectionState.Closed Then
sql.cnn.Open()
End If
Dim sqlstring As String
Dim command As New SqlCommand
sqlstring = "SELECT MAX(RIGHT(no,6)) as no from CodeTBL"
command.Connection = sql.cnn
command = New SqlCommand(sqlstring, sql.cnn)
sql.sqldr = command.ExecuteReader
sql.sqldr.Read()
If Not sql.sqldr.HasRows Or IsDBNull(sql.sqldr.Item("no")) Then
TextBox8.Text = +"000001"
Else
Dim news As Integer = CInt(sql.sqldr.Item("no"))
news += 1
TextBox8.Text = news.ToString("000000")
End If
sql.sqldr.Close()
sql.cnn.Close()
End Sub

what is the correct format for calling a db in access, with a 'folder with spaces'?

Public connstring As String = "Provider = Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\blablabla\Document\Visual Studio 2013\Project\rentalsystem\rental_db.accdb"
i placed this line of code under a module so i wont have to call it everytime. and this is the code that the code above is connected to...
Public Sub loadLVusers()
LVusers.Items.Clear()
Dim sqlcode As String = "select id_code, user_lastname, user_firstname, user_midname, user_username, user_password, user_email, user_privilege from tblUsers"
Dim sqlcomd As New OleDb.OleDbCommand(sqlcode)
sqlcomd.Connection = New OleDb.OleDbConnection(connstring)
sqlcomd.Connection.Open()
Dim DA As New OleDb.OleDbDataAdapter(sqlcomd)
Dim DS As New DataSet
DA.Fill(DS, "Pi")
If DS.Tables("Pi").Rows.Count > 0 Then
Dim Ic(100) As String
For r = 0 To DS.Tables("Pi").Rows.Count - 1
For c = 0 To DS.Tables("Pi").Columns.Count - 1
Ic(c) = DS.Tables("Pi").Rows(r)(c).ToString
Next
Dim LVI As New ListViewItem(Ic)
LVusers.Items.Add(LVI)
Next
End If
End Sub
now when the form/window that it is attached to loads, the form/window does not open. and then it highlights
sqlcomd.Connection = New OleDb.OleDbConnection(connstring)
so im guessing that has something to do with the file path format

DataGridView ScrollBar bug

When I get data for the DataGridView, my form freezes until the While loop completes, but then my scrollbar worked fine. I tried calling Application.DoEvents(); but that didn't work either.
If I get the data in a thread, then my form does not freeze, but the scrollbar disables and does not work after the While completes. I tried a BackgroundWorker but the scrollbar has a problem when using that too.
Private Sub dg()
myth = New Threading.Thread(AddressOf dgd)
myth.IsBackground = True
myth.Start()
End Sub
Private Sub dgd()
Dim x As Integer
If DataGridView1.Rows.Count = 0 Then x = 0 Else x = DataGridView1.Rows.Count
Try
Dim conn35a As New OleDbConnection("connstring")
Dim cmd35a As New OleDbCommand
cmd35a.CommandText = "Select count(*) from asd where downur Is Null"
cmd35a.CommandType = CommandType.Text
cmd35a.Connection = conn35a
conn35a.Open()
Dim returnValueaa As Integer = cmd35a.ExecuteScalar()
conn35a.Close()
Dim komut As String = "Select * from asd where downur Is Null"
Dim conn2 As New OleDbConnection("connstring")
conn2.Open()
Dim cmd2 As New OleDbCommand(komut, conn2)
Dim dr2 As OleDbDataReader = cmd2.ExecuteReader
If dr2.HasRows Then
While dr2.Read
Dim conn35 As New OleDbConnection("connstring")
Dim cmd35 As New OleDbCommand
cmd35.CommandText = "select count(*) from grid where ur = '" + dr2.Item("ur").ToString + "'"
cmd35.CommandType = CommandType.Text
cmd35.Connection = conn35
conn35.Open()
Dim returnValuea = cmd35.ExecuteScalar()
conn35.Close()
If returnValuea = 0 Then
DataGridView1.Rows.Add()
DataGridView1.Rows.Item(x).Cells(0).Value = x + 1
DataGridView1.Rows.Item(x).Cells(4).Value = "ID"
DataGridView1.Rows.Item(x).Cells(5).Value = dr2.Item("ur").ToString
DataGridView1.Rows.Item(x).Cells(6).Value = dr2.Item("ch").ToString
DataGridView1.Rows.Item(x).Cells(7).Value = dr2.Item("ti").ToString
DataGridView1.Rows.Item(x).Cells(8).Value = ".."
Dim client2 As New WebClient
Dim url As String = dr2.Item("pic").ToString
DataGridView1.Rows.Item(x).Cells(12).Value = New Bitmap(New MemoryStream(client2.DownloadData(url)))
DataGridView1.Rows.Item(x).Cells(13).Value = dr2.Item("vi")
DataGridView1.Rows.Item(x).Cells(14).Value = dr2.Item("su").ToString()
Dim con4 As New OleDbConnection("connstring")
con4.Open()
Dim cmd5 = New OleDbCommand("INSERT INTO grid (ur) VALUES (#ur)", con4)
cmd5.CommandType = CommandType.Text
cmd5.Parameters.Add("#ur", OleDbType.VarChar, 500).Value = dr2.Item("ur").ToString
cmd5.ExecuteNonQuery()
con4.Close()
x += 1
End If
End While
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I had the same problem.
I solved this by removing the Thread and calling the method directly

Sharepoont 2010 webpart vb.net Listbox SelectIndexChanged and errors

So let start I am new to coding widgets and in general. I had originally coded this in vb for asp pages and it work fine. Now converting over to a SharePoint 2010 webpart (not visual webpart).
The project is List box 1 has the user groups that they manage, List box 2 has the users in said group, List box 3 has all user not in List box 2
I am sure there lots of this that should be fix. Like not putting in admin login to get the data.
But the problem I have is: if select a group it will display the appropriate data but select a second group or select a user to add; same error.
Error:
"Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request."
Also still trying to figure out how to do the button to add a user.
Need some serious help please. I know part of the post back just having a hard time finding resources.
Below is the code:
Imports System
Imports System.ComponentModel
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.WebControls
Imports ActiveDs
Imports System.DirectoryServices
Imports System.Data
Imports ADODB
Imports System.Runtime.InteropServices
<ToolboxItemAttribute(False)> _
Public Class Groups
Inherits System.Web.UI.WebControls.WebParts.WebPart
Private LBgrp As ListBox
Private LBgrpmem As ListBox
Private LBaddgrp As ListBox
Private btnadd As Button
Protected Overrides Sub CreateChildControls()
Me.LBgrpmem = New ListBox
Me.LBgrpmem.AutoPostBack = True
Me.LBgrpmem.DataValueField = "sAMAccountName"
Me.LBgrpmem.DataTextField = "displayName"
Me.LBgrpmem.DataBind()
Me.LBgrpmem.Rows = 8
Me.LBgrpmem.Width = 170
Me.LBgrpmem.Height = 350
Me.LBgrpmem.Items.Insert(0, New ListItem("-- Current Members --"))
Me.Controls.Add(LBgrpmem)
Me.LBaddgrp = New ListBox
Me.LBaddgrp.AutoPostBack = True
Me.LBaddgrp.DataTextField = "displayName"
Me.LBaddgrp.DataValueField = "sAMAccountName"
Me.LBaddgrp.DataBind()
Me.LBaddgrp.Items.Insert(0, New ListItem("-- Add Users --"))
Me.LBaddgrp.Width = 170
Me.LBaddgrp.Height = 350
AddHandler LBaddgrp.SelectedIndexChanged, New EventHandler(AddressOf DLAdd_SelectedIndexChanged)
Me.Controls.Add(LBaddgrp)
Me.btnadd = New Button()
' AddHandler Me.btnadd.Click, New EventHandler(AddressOf Click_btnadd)
Me.btnadd.Text = "Add User"
Me.Controls.Add(btnadd)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Dim oCon As New ADODB.Connection
Dim oRecordSet As New ADODB.Recordset
Dim oCmd As New ADODB.Command
Dim sFullUser As String = Environment.UserName
Dim sProperties = "name,ADsPath,description,member,memberof,managedObjects"
Dim sGroup = "*"
Dim aMember
Dim iCount
oCon.ToString()
oCmd.ToString()
sFullUser.ToString()
sProperties.ToString()
sDomainADsPath.ToString()
oCon.Provider = "ADsDSOObject"
oCon.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd.ActiveConnection = oCon
oCmd.CommandText = "<" & sDomainADsPath & ">;(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & sFullUser & "));" & sProperties & ";subtree"
oRecordSet = oCmd.Execute
Dim de As DirectoryServices.DirectoryEntry = New DirectoryServices.DirectoryEntry(sDomainADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim i As Integer = 0
Dim sl As SortedList = New SortedList(New CaseInsensitiveComparer)
de.ToString()
While Not oRecordSet.EOF
aMember = oRecordSet.Fields("managedObjects").Value
If Not IsDBNull(aMember) Then
For iCount = 0 To UBound(aMember)
Dim groupDN As String = ("distinguishedName=" & aMember(iCount))
Dim src As DirectoryServices.DirectorySearcher = New DirectoryServices.DirectorySearcher("(&(objectCategory=Group)(" & groupDN & "))")
src.SearchRoot = de
src.SearchScope = DirectoryServices.SearchScope.Subtree
For Each res As DirectoryServices.SearchResult In src.FindAll
sl.Add(res.Properties("name")(0).ToString, i)
i += 1
Next
Next
End If
oRecordSet.MoveNext()
End While
Me.LBgrp = New ListBox
Me.LBgrp.AutoPostBack = True
Me.LBgrp.DataSource = sl
Me.LBgrp.DataTextField = "key"
Me.LBgrp.DataValueField = "value"
Me.LBgrp.DataBind()
Me.LBgrp.Items.Insert(0, New ListItem("-- Groups --"))
Me.Controls.Add(LBgrp)
Me.LBgrp.SelectedIndex = 0
AddHandler LBgrp.SelectedIndexChanged, New EventHandler(AddressOf LBgrp_SelectedIndexChanged)
LBgrp.SelectedItem.ToString()
End Sub
Protected Sub LBgrp_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles LBgrp.SelectedIndexChanged
Dim strQuery As String = "" & LBgrp.SelectedItem.Text.ToString() & "'"
'LBgrpmem.Items.Clear()
Dim oRootDSE2 = GetObject("LDAP://RootDSE")
Dim sDomainADsPath2 = "LDAP://" & oRootDSE2.Get("defaultNamingContext")
Dim oCon2 As New ADODB.Connection
Dim oRecordSet2 As New ADODB.Recordset
Dim sFullUser2 As String = Environment.UserName
Dim oCmd2 As New ADODB.Command
Dim sProperties2 = "name,ADsPath,description,member,memberof,managedObjects"
Dim grpADsPath2
Dim grpdsplynm2
oRootDSE2 = Nothing
oCon2.Provider = "ADsDSOObject"
oCon2.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd2.ActiveConnection = oCon2
oCmd2.CommandText = "<" & sDomainADsPath2 & ">;(&(objectCategory=group)(objectClass=group)(CN=" & LBgrp.SelectedItem.Text & "));" & sProperties2 & ";subtree"
oRecordSet2 = oCmd2.Execute
While oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
grpADsPath2.ToString()
grpdsplynm2 = grpADsPath2.remove(0, 7)
grpdsplynm2.ToString()
oRecordSet2.MoveNext()
End While
While Not oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
grpADsPath2.ToString()
grpdsplynm2 = grpADsPath2.remove(0, 7)
grpdsplynm2.ToString()
oRecordSet2.MoveNext()
End While
Dim groupDN2 As String = "" & grpdsplynm2 & ""
Dim filter As String = [String].Format("(&(objectClass=user)(objectCategory=person)(memberOf={0}))", groupDN2)
Me.LBgrpmem.AutoPostBack = True
Me.LBgrpmem.DataSource = FindUsers(filter, New String() {"sAMAccountName", "displayName"}, sDomainADsPath2, True)
Me.LBgrpmem.DataValueField = "sAMAccountName"
Me.LBgrpmem.DataTextField = "displayName"
Me.LBgrpmem.DataBind()
Me.LBgrpmem.Items.Insert(0, New ListItem("-- Current Members --"))
Me.Controls.Add(LBgrpmem)
Dim usrDN As String = "" & grpdsplynm2 & ""
usrDN.ToString()
Dim usrfilter As String = [String].Format("(&(objectClass=user)(objectCategory=person)(!memberOf={0}))", groupDN2)
Me.LBaddgrp.AutoPostBack = True
Me.LBaddgrp.DataSource = FindUsers(usrfilter, New String() {"sAMAccountName", "displayName"}, sDomainADsPath2, True)
Me.LBaddgrp.DataTextField = "displayName"
Me.LBaddgrp.DataValueField = "sAMAccountName"
Me.LBaddgrp.DataBind()
Me.LBaddgrp.Items.Insert(0, New ListItem("-- Add Users --"))
'AddHandler LBaddgrp.SelectedIndexChanged, New EventHandler(AddressOf DLAdd_SelectedIndexChanged)
Me.Controls.Add(LBaddgrp)
End Sub
Public Function FindUsers(ByVal sFilter As String, ByVal columns() As String, ByVal path As String, ByVal useCached As Boolean) As Data.DataSet
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
'try to retrieve from cache first
Dim context As HttpContext = HttpContext.Current
Dim userDS As Data.DataSet = CType(context.Cache(sFilter), Data.DataSet)
If userDS Is Nothing Or Not useCached Then
'setup the searching entries
Dim deParent As New DirectoryServices.DirectoryEntry(sDomainADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim ds As New DirectoryServices.DirectorySearcher(deParent, sFilter, columns, DirectoryServices.SearchScope.Subtree)
ds.PageSize = 1000
ds.Sort.PropertyName = "displayName" 'sort option
Using (deParent)
userDS = New Data.DataSet("userDS")
Dim dt As Data.DataTable = userDS.Tables.Add("users")
Dim dr As Data.DataRow
'add each parameter as a column
Dim prop As String
For Each prop In columns
dt.Columns.Add(prop, GetType(String))
Next prop
Dim src As DirectoryServices.SearchResultCollection = ds.FindAll
Try
Dim sr As DirectoryServices.SearchResult
For Each sr In src
dr = dt.NewRow()
For Each prop In columns
If sr.Properties.Contains(prop) Then
dr(prop) = sr.Properties(prop)(0)
End If
Next prop
dt.Rows.Add(dr)
Next sr
Finally
src.Dispose()
End Try
End Using
'cache it for later, with sliding window
context.Cache.Insert(sFilter, userDS, Nothing, DateTime.MaxValue, TimeSpan.FromSeconds(10))
End If
Return userDS
End Function 'FindUsers
Protected Sub DLAdd_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles Click_btnadd
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Dim oCon As New ADODB.Connection
Dim oRecordSet As New ADODB.Recordset
Dim oRcrdSet As New ADODB.Recordset
Dim oCmd As New ADODB.Command
Dim oCmd1 As New ADODB.Command
Dim sGroup = "*"
Dim sProperties = "name,ADsPath,description,member,memberof,proxyAddresses"
Dim grpADsPath
Dim grpdsplynm
Dim addusrADsPath
Dim addusrname
oRootDSE = Nothing
oCon.Provider = "ADsDSOObject"
oCon.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd.ActiveConnection = oCon
oCmd1.ActiveConnection = oCon
oCmd.CommandText = "<" & sDomainADsPath & ">;(&(objectClass=group)(cn=" & LBgrp.SelectedItem.Text & "));" & sProperties & ";subtree"
oRecordSet = oCmd.Execute
'Group Query
While Not oRecordSet.EOF
grpADsPath = oRecordSet.Fields("ADsPath").Value
grpdsplynm = oRecordSet.Fields("name").Value
oRecordSet.MoveNext()
End While
oCmd1.CommandText = "<" & sDomainADsPath & ">;(&(objectCategory=person)(objectClass=user)(cn=" & LBaddgrp.SelectedItem.Text & "));" & sProperties & ";subtree"
oRcrdSet = oCmd1.Execute
'User query
While Not oRcrdSet.EOF
addusrADsPath = oRcrdSet.Fields("ADsPath").Value
addusrname = oRcrdSet.Fields("name").Value
oRcrdSet.MoveNext()
End While
' Bind directly to the group
'
Dim oRootDSE2 = GetObject("LDAP://RootDSE")
Dim sDomainADsPath2 = "LDAP://" & oRootDSE2.Get("defaultNamingContext")
Dim oCon2 As New ADODB.Connection
Dim oRecordSet2 As New ADODB.Recordset
Dim sFullUser2 As String = Environment.UserName
'Dim sFullUser2 = Request.ServerVariables("LOGON_USER")
'Dim sUser2 = Split(sFullUser2, "\", -1)
Dim oCmd2 As New ADODB.Command
Dim sProperties2 = "name,ADsPath,description,member,memberof,managedObjects"
Dim grpADsPath2
oRootDSE2 = Nothing
oCon2.Provider = "ADsDSOObject"
oCon2.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd2.ActiveConnection = oCon2
oCmd2.CommandText = "<" & sDomainADsPath2 & ">;(&(objectCategory=group)(objectClass=group)(CN=" & LBgrp.SelectedItem.Text & "));" & sProperties2 & ";subtree"
oRecordSet2 = oCmd2.Execute
While Not oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
oRecordSet2.MoveNext()
End While
Dim group As New DirectoryServices.DirectoryEntry("" & grpADsPath2 & "", "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim user As New DirectoryServices.DirectoryEntry(addusrADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim isMember As Boolean = Convert.ToBoolean(group.Invoke("IsMember", New Object() {user.Path}))
If isMember Then
'
' TO CREATE ERROR MESSAGE
Else
' Add the user to the group by invoking the Add method
'
group.Invoke("Add", New Object() {user.Path})
End If
If Not IsNothing(user) Then
user.Dispose()
End If
If Not IsNothing(group) Then
group.Dispose()
End If
Console.ReadLine()
If (Err.Number <> 0) Then
' TO CREATE ERROR MESSAGE
Else
' TO CREATE SUCCESS MESSAGE
End If
End Sub
Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)
LBgrp.RenderControl(writer)
LBgrpmem.RenderControl(writer)
LBaddgrp.RenderControl(writer)
btnadd.RenderControl(writer)
End Sub
End Class
if memory serves me correctly, Page_Load event is firing on a postback too, where you are trying to create another instance of your drop down. So the system is trying to recreate the state of ListBox from ViewState but it is not the same ListBox, because you have just recreated it. So it barks.
To avoid it, in the page_load only create "parent" drop down if it's not postback. i.e.
Begin Page_Load()
If !Page.IsPostBack() Then
'load code here
End If
End Page_Load
Also there's no need to write
Me.LBgrpmem = New ListBox
as it is already created. Changing the datasource is usually enuff.

Why do I get the error: System.Runtime.InteropServices.COMException?

I am using VB.NET to Create Labels in Microsoft. This is my code:
Public Sub CreateLabel(ByVal StrFilter As String, ByVal Path As String)
WordApp = CreateObject("Word.Application")
''Add a new document.
WordDoc = WordApp.Documents.Add()
Dim oConn As SqlConnection = New SqlConnection(connSTR)
oConn.Open()
Dim oCmd As SqlCommand
Dim oDR As SqlDataReader
oCmd = New SqlCommand(StrFilter, oConn)
oDR = oCmd.ExecuteReader
Dim intI As Integer
Dim FilePath As String = ""
With WordDoc.MailMerge
With .Fields
Do While oDR.Read
For intI = 0 To oDR.FieldCount - 1
.Add(WordApp.Selection.Range, oDR.Item(intI))
Next
Loop
End With
Dim objAutoText As Word.AutoTextEntry = WordApp.NormalTemplate.AutoTextEntries.Add("MyLabelLayout", WordDoc.Content)
WordDoc.Content.Delete()
.MainDocumentType = Word.WdMailMergeMainDocType.wdMailingLabels
FilePath = CreateSource(StrFilter)
.OpenDataSource(FilePath)
Dim NewLabel As Word.CustomLabel = WordApp.MailingLabel.CustomLabels.Add("MyLabel", False)
WordApp.MailingLabel.CreateNewDocument(Name:="MyLabel", Address:="", AutoText:="MyLabelLayout")
objAutoText.Delete()
.Destination = Word.WdMailMergeDestination.wdSendToNewDocument
WordApp.Visible = True
.Execute()
End With
oConn.Close()
WordDoc.Close()
End Sub
Private Function CreateSource(ByVal StrFilter As String) As String
Dim CnnUser As SqlConnection = New SqlConnection(connSTR)
Dim sw As StreamWriter = File.CreateText("C:\Mail.Txt")
Dim Path As String = "C:\Mail.Txt"
Dim StrHeader As String = ""
Try
Dim SelectCMD As SqlCommand = New SqlCommand(StrFilter, CnnUser)
Dim oDR As SqlDataReader
Dim IntI As Integer
SelectCMD.CommandType = CommandType.Text
CnnUser.Open()
oDR = SelectCMD.ExecuteReader
For IntI = 0 To oDR.FieldCount - 1
StrHeader &= oDR.GetName(IntI) & " ,"
Next
StrHeader = Mid(StrHeader, 1, Len(StrHeader) - 2)
sw.WriteLine(StrHeader)
sw.Flush()
sw.Close()
StrHeader = ""
Do While oDR.Read
For IntJ As Integer = 0 To oDR.FieldCount - 1
StrHeader &= oDR.GetString(IntJ) & " ,"
Next
Loop
StrHeader = Mid(StrHeader, 1, Len(StrHeader) - 2)
sw = File.AppendText(Path)
sw.WriteLine(StrHeader)
CnnUser.Close()
sw.Flush()
sw.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "TempID", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return Path
End Function
Now when I am running the program I am getting this error. I tried hard but not able to locate what could be the problem the error is:
System.Runtime.InteropServices.COMException -->Horizontal and vertical
pitch must be greater than or equal to the label width and height,
respectively.
Even though I tried to set the Horizontal and vertical pitch programatically it gives same error.
Make sure that you have a default printer set up for the user account that the application runs under. Might not be relevant but I have had various unusual problems following that omission.
Did you install the Office Primary Interop Assemblies? (Appropriately abbreviated to PIA)
Try this