How to pass values to two different parameters - vb.net

I am developing a Windows Application and use a Crystal Report in it.
I am able to pass value to one parameter of Crystal Report. Now, I have added one more parameter to Crystal Report, but confused about what modification I have to make in below code.
Below code is written to pass value to one parameter of CR.
Private Sub btnLoadBatch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadBatch.Click
Try
Dim cr As New crMonthwiseBatch
Dim oBatches As New Batches
Dim Month As Integer = dtFrom.Value.Date.Month
Dim StartDateForBatch As Date = New DateTime(dtBatchStartFromMonth.Value.Year, dtBatchStartFromMonth.Value.Month, "1")
Dim DaysinMonths As Integer = System.DateTime.DaysInMonth(dtBatchStartFromMonth.Value.Year, dtBatchStartFromMonth.Value.Month)
Dim EndDateForBatch = StartDateForBatch.AddDays(DaysinMonths)
oBatches.LoadByQuery("CreatedDate >= #" + StartDateForBatch + "# and CreatedDate <= #" + EndDateForBatch + "#")
cr.SetDataSource(oBatches)
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = "Batch List of Month - " + MonthName(dtBatchStartFromMonth.Value.Month) + " " + dtBatchStartFromMonth.Value.Year.ToString
crParameterFieldDefinitions = cr.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("MonthName")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
CrystalReportViewerMonthwiseBatch.ReportSource = cr
CrystalReportViewerMonthwiseBatch.Refresh()
Catch ex As Exception
End Try
End Sub

You can achieve it this way (look for comments above statement(s) for description)
Approach 1:
'...
'collection of objects for every parameter field
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
'represent a parameter field
Dim crParameterFieldDefinition As ParameterFieldDefinition
'collection of ParameterValue objects for every parameter field
Dim crParameterValues As New ParameterValues()
'for retrieving and setting discrete value parameters
Dim crParameterDiscreteValue As New ParameterDiscreteValue()
'get parameters collection in current crystal report
crParameterFieldDefinitions = cr.DataDefinition.ParameterFields
'adding FIRST parameter
'get the parameter in the current report and assign a value
crParameterFieldDefinition = crParameterFieldDefinitions("PARAM_1_NAME")
crParameterDiscreteValue.Value = "PARAM_1_VALUE"
crParameterValues = crParameterFieldDefinition.CurrentValues
'clear old/default values assigned to current parameter, add and apply new value
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
'finished adding FIRST parameter
'adding SECOND and subsequent parameters
'reset the collections
crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterValues = New ParameterValues()
'get parameter, assign values, clear old values, add to collection and apply
crParameterFieldDefinition = crParameterFieldDefinitions("PARAM_2_NAME")
crParameterDiscreteValue.Value = "PARAM_2_VALUE"
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
'finished adding SECOND parameter
'...
'Just display the report
Approach 2:
If you have multiple parameters it can also be achieved by using a separate procedure such as
Private Sub SetParams(crRpt As CrystalDecisions.CrystalReports.Engine.ReportDocument, strParamName As String, strParamValue As String)
For Each pfField As CrystalDecisions.CrystalReports.Engine.ParameterFieldDefinition In crRpt.DataDefinition.ParameterFields
If pfField.Name.ToString().ToLower() = strParamName.ToLower() Then
Try
Dim crParameterValues As New CrystalDecisions.Shared.ParameterValues()
Dim crParameterDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue()
crParameterDiscreteValue.Value = strParamValue
crParameterValues = pfField.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
pfField.ApplyCurrentValues(crParameterValues)
Catch ex As Exception
'add your exception handling mechanism here
MessageBox.Show(ex.Message)
End Try
End If
Next
End Sub
The above routine can be called for any report object (as cr in example below) to add any number of parameters to the reports
SetParams(cr, "#Param_1_Name", "Param_1_Value")
SetParams(cr, "#Param_2_Name", "Param_2_Value")
'...
SetParams(cr, "#Param_n_Name", "Param_n_Value")

Related

Crystal Report always asking to enter parameter value

I am having a problem passing the combobox value to crystal report I am kinda newbie with the crystal report so I really need your help guys!
here is my code:
dir = Path.GetFullPath(dir)
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
Dim reportsfolder As String = Application.StartupPath + "\PrintArea\LoanProdReport.rpt"
Dim report As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim DS As New DataSet
Dim query As String
query = "SELECT * FROM ClientDatabase"
Dim DA As New SqlDataAdapter(query, jonsqlcon)
DA.Fill(DS)
report.Load(reportsfolder)
report.SetDatabaseLogon(dbSettingsAdder.TBUserID.Text, dbSettingsAdder.tbPassword.Text)
crParameterFieldDefinitions = report.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("YearHeader")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterDiscreteValue.Value = ComboBoxEx2.SelectedItem.ToString
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
report.SetDataSource(DS.Tables(0))
LoanProdRpt.CrystalReportViewer1.ReportSource = report
LoanProdRpt.CrystalReportViewer1.Refresh()
LoanProdRpt.ShowDialog()
and here is the Screenshot of my Report
as you can see I am trying to pass the Combobox value into parameter YearHeader.
Any help will be appreciated. Thanks in Advance :)
How silly of me, I just did it like this
dir = Path.GetFullPath(dir)
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
Dim reportsfolder As String = Application.StartupPath + "\PrintArea\LoanProdReport.rpt"
Dim report As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim DS As New DataSet
Dim query As String
query = "SELECT * FROM ClientDatabase"
Dim DA As New SqlDataAdapter(query, jonsqlcon)
DA.Fill(DS)
report.Load(reportsfolder)
report.SetDatabaseLogon(dbSettingsAdder.TBUserID.Text, dbSettingsAdder.tbPassword.Text)
report.SetDataSource(DS.Tables(0))
crParameterFieldDefinitions = report.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("YearHeader")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterDiscreteValue.Value = ComboBoxEx2.SelectedItem.ToString
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
LoanProdRpt.CrystalReportViewer1.ReportSource = report
LoanProdRpt.CrystalReportViewer1.Refresh()
LoanProdRpt.ShowDialog()

VB.NET Getting All Items in ListBox and Pass to a Parameter

Hi I'm stuck with my loop passing all items in my listbox to a crystal report parameter.
For i = 0 To ListBoxBillAccount.Items.Count - 1
If ListBoxBillAccount.Items(i).selected Then
crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterDiscreteValue.Value = ListBoxBillAccount.SelectedItems()
crParameterValues.Add(crParameterDiscreteValue)
End If
Next
I'm getting an error: "Public member 'selected' on type 'DataRowView' not found."
Edit: Here's my full code:
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterFieldDefinitions = crReportDoc.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions("UserAcct")
crParameterValues = crParameterFieldDefinition.CurrentValues
For i = 0 To ListBoxBillAccount.Items.Count - 1
If ListBoxBillAccount.Items(i).selected Then
crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterDiscreteValue.Value = ListBoxBillAccount.SelectedItems()
crParameterValues.Add(crParameterDiscreteValue)
End If
Next
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
frmGenerateConsolidatedBill.CrystalReportViewer1.ReportSource = crReportDoc
frmGenerateConsolidatedBill.Refresh()
frmGenerateConsolidatedBill.Show()
Perhaps:
For Each obj In ListBoxBillAccount.SelectedItems()
Dim crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterDiscreteValue.Value = obj
crParameterValues.Add(crParameterDiscreteValue)
Next

Passing Multiple Values to a single Crystal Reports parameter from VB.net

I am using Visual Basic in Visual Studio 2012 with Crystal Reports for Visual Studio.
I have a parameter in a Crystal Report that can accept multiple values (for instance: Regions). How do I pass multiple values to that single parameter from vb.net? The values would be coming from selections from a ListBox.
Sorry if this is answered elsewhere. I have tried many searches all over internet with no luck.
Thanks in advance!
Bob
As asked for, here is code from where I select a single value from ComboBox. The Parameter in the Crystal Report is BuyDate. I just am not sure how to make it for multiple values. If you need more details, just let me know.
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
Dim SSBuy = New CrystalDecisions.CrystalReports.Engine.ReportDocument()
Dim Filepath = "\\filepath\Report By Buy Date.rpt"
SSBuy.Load(Filepath)
crParameterDiscreteValue.Value = ComboBox1.SelectedItem
crParameterFieldDefinitions = SSBuy.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("BuyDate")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
SSBuyForm.CrystalReportViewer1.ReportSource = SSBuy
SSBuyForm.Refresh()
SSBuyForm.Show()
I was able to find the answer on the SAP website. Here is the link to the article, for anyone else who may need it.
Pass Multiple Values to a Parameter
Also, here is the actual code I used, which runs a report based on PO#'s selected from a ListBox.
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
Dim SSPO = New CrystalDecisions.CrystalReports.Engine.ReportDocument()
Dim Filepath = "\\Filepath\Report Download By PO #.rpt"
SSPO.Load(Filepath)
crParameterFieldDefinitions = SSPO.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions("PO#")
crParameterValues = crParameterFieldDefinition.CurrentValues
Dim Count As Integer = POList1.SelectedItems.Count
For i = 0 To Count - 1
If i > 0 Then
crParameterDiscreteValue = Nothing
End If
crParameterDiscreteValue = New ParameterDiscreteValue()
crParameterDiscreteValue.Value = POList1.SelectedItems(i)
crParameterValues.Add(crParameterDiscreteValue)
Next
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
SSPoForm.CrystalReportViewer1.ReportSource = SSPO
SSPoForm.Refresh()
SSPoForm.Show()

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.

passing date range parameters from a vb.net windows application

I need to pass date range parameters to a crystal report from a vb.net application, but I don't know how to. For anyone who may want to help me, please base yourself on the following scenario:
I have a crystal report that pulls data from an oracle database. In the database, I have a table of students, and each record has a birth date, name and surname. I need to display on the report only records where the birth date is between date X and date Y inclusive of both. Date X and Date Y are dates passed on the vb.net application when opening the report.
I am using crystal reports 9, visual studio 2008 and oracle 9i.
Somebody please help me out, how do I achieve this?
Assuming your Crystal Report is bound to an SQL Command, say:
SELECT name, surname FROM students WHERE birthdate BETWEEN {?#pDate1} AND {?#pDate2}
From VB.NET, you need to pass parameters as below:
Private rptSummary As New ReportDocument()
Protected Sub Page_Init(sender As Object, e As EventArgs)
Try
Dim pFields As New ParameterFields()
Dim pField_Date1 As New ParameterField()
Dim pField_Date2 As New ParameterField()
Dim pDiscreteValue_Date1 As New ParameterDiscreteValue()
Dim pDiscreteValue_Date2 As New ParameterDiscreteValue()
Dim ApplPath As String = Server.MapPath("MyReport.rpt")
rptSummary.FileName = ApplPath
pField_Date1.Name = "#pDate1"
pField_Date2.Name = "#pDate2"
Dim BirthDate1, BirthDate2
' Parameter: #pDate1
pDiscreteValue_Date1.Value = BirthDate1
pField_Date1.CurrentValues.Add(pDiscreteValue_Date1)
pFields.Add(pField_Date1)
' Parameter: #pDate2
pDiscreteValue_Date2.Value = BirthDate2
pField_Date2.CurrentValues.Add(pDiscreteValue_Date2)
pFields.Add(pFieldDate2)
CrystalReportViewer1.ParameterFieldInfo = pFields
rptSummary.SetParameterValue(0, pDiscreteValue_Date1)
rptSummary.SetParameterValue(1, pDiscreteValue_Date2)
CrystalReportViewer1.ReportSource = rptSummary
Catch ex As Exception
End Try
End Sub
This code is originally in ASP.NET with C#. I converted it to VB.NET. Please correct any discrepancies.
Just create a crystal report with required parameters and create button, datetimepicker for from date and to date in the from.
insert the code for button click.
Working perfectly for me..............
If any mistakes modify..
Thank Q
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt1 As New ReportDocument
Dim str As String = System.AppDomain.CurrentDomain.BaseDirectory
str = str.Substring(0, str.Length - 10)
cryRpt1.Load(str & "daily_scrl_rep.rpt")
cryRpt1.SetParameterValue(0, DTPFrom.Text)
cryRpt1.SetParameterValue(1, DTPTO.Text)
CrystalReportViewer1.ReportSource = cryRpt1
CrystalReportViewer1.Refresh()
End Sub
Just 2 Lines will be enough
rptSummary.SetParameterValue("your report perameter name", your value 1st value)
rptSummary.SetParameterValue("your report perameter name", your value 2nd value)
Thats it.
string rang1 = Session["Rang1"].ToString();
string rang2 = Session["Rang2"].ToString(); ;
ReportDocument obj = new ReportDocument();
obj.Load(Server.MapPath("~/CType_CrystalReport.rpt"));
obj.SetDatabaseLogon("sa", "12qwaszx", "BTS-10", "BTS_ERP");
ParameterFields paraf = new ParameterFields();
ParameterField par = new ParameterField();
ParameterField par2 = new ParameterField();
par.ParameterFieldName = "CtCode";
ParameterDiscreteValue dcpara1 = new ParameterDiscreteValue();
ParameterDiscreteValue dcpara2 = new ParameterDiscreteValue();
par.Name = rang1;
par2.Name = rang2;
dcpara1.Value = rang1.ToString();
par.CurrentValues.Add(dcpara1);
paraf.Add(par);
dcpara2.Value = rang2.ToString();
par2.CurrentValues.Add(dcpara2);
paraf.Add(par2);
CrystalReportViewer1.ParameterFieldInfo = paraf;
obj.SetParameterValue("CtCode", dcpara1);
obj.SetParameterValue("CtCode", dcpara2);
CType_DataSet dsCustomers = GetData("select * from GL_CUSTTYPE where CT_CODE between '" + rang1.ToString() + "' AND '" + rang2.ToString() + "' ");
obj.SetDataSource(dsCustomers);
CrystalReportViewer1.ReportSource = obj;
CrystalReportViewer1.RefreshReport();
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Dim crtableLogoninfos As New CrystalDecisions.Shared.TableLogOnInfos()
Dim crtableLogoninfo As New CrystalDecisions.Shared.TableLogOnInfo()
Dim crConnectionInfo As New CrystalDecisions.Shared.ConnectionInfo()
Dim crit As String
Dim CrTables As Tables
Dim CrTable As Table
reportdocument.Load(Server.MapPath("~/Reports/IssueReport.rpt"))
CrTables = reportdocument.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
CrTable.Location = crConnectionInfo.DatabaseName & ".dbo." & CrTable.Location.Substring(CrTable.Location.LastIndexOf(".") + 1)
Next
Crit = "{tablename.fieldname}>=#" & Format(CDate(txtfromdate.Text), "yyyy/MM/dd") & "#"
Crit = Crit & " and {tablename.fieldname} <=#" & Format(CDate(txtto.Text), "yyyy/MM/dd") & "#"
reportdocument.RecordSelectionFormula = Crit
CrystalReportViewer1.ReportSource = reportdocument
CrystalReportViewer1.RefreshReport()