Click here to Skip to main content
Click here to Skip to main content

Dynamic Creation Of MenuStrip - VB.NET

By , 23 Aug 2008
 

Introduction

I came up with the problem of creating an application that was driven according to user rights. I thought of implementing the menus to be driven through BackEnd. All the menu names and the form (formname) to open when the child menu was clicked, come from the table. To implement menus, I used MenuStrip from VB.NET.

Sample Code

Using the Code

It executes during the Form Load and populates all the menu headers. All data comes from the backend and there is nothing to hardcode. I have attached the structure of two tables MENUMASTER and ACCESS below.

The code below will have a variable like iUserAccessMode, which in turn tells us about the user access level (Look into the Excel sheet which has been attached and look into the Access Tab in the Excel sheet). The Menus will be loaded according to User Access Level.

 Private Sub MDIParent1_Load(ByVal sender As Object,
        ByVal e As System.EventArgs) Handles Me.Load
        'On Error GoTo ErrHandler
 'Create a Connection class, that has the full features of working with Backend.
 'See article for Connection class :  Connection_Class.asp
 
        Dim Conn As New Conn1
        Dim mnRd As SqlClient.SqlDataReader
 'It helps in populating the MENUs according to user rights. From the Table "Access"
        iUserAccessMode = GlobalValues.lblUsrAccess.Text
        sQry = ""
        sQry = "Select MenuText from MenuMaster Where MainMenuID = 0" & _
               " And MenuID in (Select MenuID from Access Where AccessId =
                " & CInt(iUserAccessMode) & ")" & _
                " And isActive = 1"
        mnRd = Conn.ReaderData(sQry)
        
 If mnRd.HasRows Then
            mnMenu = New MenuStrip
            While mnRd.Read
                mnMenu.Items.Add(mnRd(0).ToString, Nothing, New System.EventHandler(
                    AddressOf MainMenu_OnClick))
                Me.Controls.Add(mnMenu)
            End While
        End If
        
 mnRd.Close()
    End Sub

This function creates child menus when the parent menu is created.

Private Sub MainMenu_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim cms As New ContextMenuStrip()
        Dim sMenu() As String
        Dim Conn As New Conn1
        Dim sMenuRD As SqlClient.SqlDataReader
        sQry = ""
        sQry = "Select MenuID from MenuMaster Where MenuText = '" & sender.ToString & "'"
        sMenuRD = Conn.ReaderData(sQry)
        Dim parentMenuID As Integer
        If sMenuRD.HasRows Then
            sMenuRD.Read()
            parentMenuID = sMenuRD("MenuID")
        End If
        sMenuRD.Close()
        sQry = ""
        sQry = "Select MenuText from MenuMaster Where MainMenuID =
               '" & parentMenuID & "'" & _
               " And isActive = 1" & _
               " And MenuID in (
                   Select MenuID from Access Where AccessId =
                   " & CInt(iUserAccessMode) & ")" & _
               " Order BY MenuOrder"
        sMenuRD = Conn.ReaderData(sQry)
        ReDim Preserve sMenu(0)
        Dim i As Integer
        If sMenuRD.HasRows Then
            ReDim Preserve sMenu(0)
            i = 0
            While sMenuRD.Read()
                ReDim Preserve sMenu(i)
                sMenu(i) = sMenuRD("MenuText")
                i = i + 1
            End While
        End If
        sMenuRD.Close()
        For Each sMn As String In sMenu
            cms.Items.Add(sMn, Nothing,
                New System.EventHandler(AddressOf SelectedChildMenu_OnClick))
        Next
        Dim tsi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
        tsi.DropDown = cms
    End Sub

This function is executed at the click event of each menu item, the form to open(FormName) on the execution of the event also comes from the backend table "MENUMASTER".

    Private Sub SelectedChildMenu_OnClick(ByVal sender As Object,
        ByVal e As System.EventArgs)
        Dim Conn As New Conn1
        Dim sMenuRD As SqlClient.SqlDataReader
        Dim frmName As String = ""
        Dim frm As New Form
        sQry = ""
        sQry = "Select FormName from MenuMaster Where MenuText = '" &
            sender.ToString & "'"
        sMenuRD = Conn.ReaderData(sQry)
        If sMenuRD.HasRows Then
            sMenuRD.Read()
            frmName = sMenuRD(0).ToString
            DynamicallyLoadedObject(frmName).Show(Me)
        Else
            MsgBox("Under Construction", MsgBoxStyle.Exclamation, "Technical Error")
        End If
        sMenuRD.Close()
    End Sub

Points of Interest

I came up with the problem of converting the formname which I get from SQL as string to FORM object. This function helps in converting the string object formName, which is returned from SQL into object of type Form:

    Private Function DynamicallyLoadedObject(ByVal objectName As String,
        Optional ByVal args() As Object = Nothing) As Form
        Dim returnObj As Object = Nothing
        Dim Type As Type = Assembly.GetExecutingAssembly().GetType(
            "[YOUR PROJECT NAME]." & objectName)
        If Type IsNot Nothing Then
            returnObj = Activator.CreateInstance(Type, args)
        End If
        Return returnObj
    End Function

History

  • 17th June, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Bad Programmer
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionObject reference not set to an instance of an objectmemberajay170615 Dec '12 - 21:50 
Dear ,

Can you provide the solution? I also got this message "Object reference not set to an instance of an object."

Your help is much appreciated.
 
Regards,
Ajay.

QuestionPlease help...membershahidzahoor22 Aug '12 - 20:32 
hi... am new to development... i read your article.. its very help full. but i dont know where to right this iUSerAcess variable... can some one help me to fully understand this article.
 
Regards..
QuestionProbleme sur menu dynamiquememberabraoui20 Jul '12 - 2:42 
Bonjour
d'après l'utilisation du code et la base j'ai rencontré une erreur au moment de l’exécution et juste lorsque je clique sur une option du menu pour charger une form déclaré sur la table (La référence d'objet n'est pas définie à une instance d'un objet)
Merci .
QuestioniUserAccessMode ?membershahidzahoor18 Jul '12 - 9:30 
what is this.. am new to development... please help me
Questionhow to add icon to the menustrip itemmembersiva778418 Aug '11 - 0:39 
how to add icon to the menustrip item
GeneralObject reference not set to an instance of an object.memberAlicealiciasawarak28 Mar '11 - 15:23 
I got this error when I click on the select menu
 
And it point to this
DynamicallyLoadedObject(frmName).Show(Me)
 
Can you please assist what I need to add or do to solve this.
GeneralRe: Object reference not set to an instance of an object.memberTheXeon198112 Nov '11 - 5:26 
i have this error Frown | :-(
GeneralName 'Assembly' is not declaredmemberAlicealiciasawarak28 Mar '11 - 2:12 
I got this message when I run the program
Name 'Assembly' is not declared.
 
Can I know how to solve this error?
GeneralRe: Name 'Assembly' is not declaredmemberBad Programmer31 Mar '11 - 12:03 
check if you have all the necessary namespaces included for usig Assembly
Bad Programmer

Questionhow to show the 3 level menumembery2yawar12 Jan '10 - 19:10 
i use your code its work greatly but i when i add 3 level menu some time its show and some time not
so kindly help me how i show it all time when i click
 

like this
(1 level) Parameter->
(2 level) Maintainence ->
(3 level) form name
GeneralMainMenu twice click from first form loadmemberMember 272868324 Jul '09 - 1:28 
Hi, very thanks for Dynamic MenuStrip code.I have a question..
Wyh open child menu twice click MainMenu button Form first load.?
Good Works/Thanks.
QuestionRe: MainMenu twice click from first form loadmemberJuan Camilo Arboleda1 Aug '09 - 16:10 
Hi, Is there any form of modify this code just to make one clic insted of two(the first time after load of the form).
AnswerRe: MainMenu twice click from first form loadmemberMark Denson16 Nov '09 - 6:58 
Easiest way is to add the following as the last line MainMenu_OnClick:
 
tsi.ShowDropDown()
GeneralRe: MainMenu twice click from first form loadmemberwallaces52816 Nov '09 - 16:52 
I have the same problem.
When i first time to click MainMenuItem, nothing happening,
when i second time to click MainMenuItem, ChildMenu was show,
and i append
tsi.ShowDropDown()
behind
tsi.DropDown = cms
at MainMenu_OnClick function, it's work correctly.
 
Thanks a lot.
GeneralDynamic Creation Of MenuStrip - C#.NETmemberSameeraMadhawa23 Jul '09 - 22:34 
can any one help me to translate this code in to C#.net.
 
best regards
Madhawa
GeneralRe: Dynamic Creation Of MenuStrip - C#.NETmemberMoises Torres10 Sep '09 - 10:44 
Maybe..... Check This I can't more.. U continueCool | :cool:
 
private void MDI_padre_Load(object sender, EventArgs e)
{
 
AccesoDatos.AccesoDatos dac = new AccesoDatos.AccesoDatos();
 
// iUserAccessMode = GlobalValues.lblUsrAccess.Text;
// iUserAccessMode = GlobalValues.lblUsrAccess.Text;
// sQry = ""
 
DataSet ds_nomMenu = dac.EjecutarConsulta("SELECT MenuText FROM MenuMaster WHERE MainMenuID = 0 AND MenuID IN (SELECT MenuID FROM Access WHERE AccessId ="+id_accces+") AND isActive = 1");
 
//sQry = "Select MenuText from MenuMaster Where MainMenuID = 0 And MenuID in (Select MenuID from Access Where AccessId ="+id_accces+") and isActive = 1";
 
// mnRd = Conn.ReaderData(sQry)
int num = ds_nomMenu.Tables[0].Rows.Count;
if (num>0)
{


//If mnRd.HasRows Then
 
MenuStrip mnMenu = new MenuStrip();
 
//

int i;
while (i <= num)
// While mnRd.Read
 
{
// mnMenu.Items.Add(mnRd(0).ToString, Nothing, New System.EventHandler(
 
mnMenu.Items.Add(ds_nomMenu.Tables[0].Rows[i]["MenuText"].ToString(), null, new System.EventHandler(MainMenu_OnClick));
// AddressOf MainMenu_OnClick))
 
this.Controls.Add(mnMenu);
// Me.Controls.Add(mnMenu)
 
// End While
i++;
// End If
}
//mnRd.Close()
}
}
 
private void MainMenu_DoubleClick(object sender, EventArgs e)
{
 
}
// Private Sub MainMenu_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
private void MainMenu_OnClick(object sender, EventArgs e)
{
string sMenu;
ContextMenuStrip cms = new ContextMenuStrip();
AccesoDatos.AccesoDatos dac = new AccesoDatos.AccesoDatos();
DataSet ds_MenuId= dac.EjecutarConsulta("Select MenuID from MenuMaster Where MenuText = '" + sender.ToString()+ "'","Table");
int parentMenuID;
if (ds_MenuId.Tables[0].Rows.Count > 0)
{
parentMenuID = Convert.ToInt32( ds_MenuId.Tables[0].Rows[0]["MenuId"].ToString());
 
}
DataSet ds_MenuText= dac.EjecutarConsulta( "Select MenuText from MenuMaster Where MainMenuID ='" + parentMenuID + "' And isActive = 1 And MenuID in (Select MenuID from Access Where AccessId =" + iUserAccessMode + ") Order BY MenuOrder","Table");
 
Array.Resize(ref sMenu, 1);
int i;
if (ds_MenuText.Tables[0].Rows.Count>0)
{
Array.Resize(ref sMenu, 1);
i = 0; while (sMenuRD.Read())
{
Array.Resize(ref sMenu, i + 1);
sMenu(i) = sMenuRD("MenuText");
i = i + 1;
}

}
foreach (string sMn in sMenu)
{
cms.Items.Add(sMn, null, new System.EventHandler(SelectedChildMenu_OnClick));
}

 
}

 

private void SelectedChildMenu_OnClick(object sender, System.EventArgs e)
{
 
string frmName = "";
Form frm = new Form();
sQry = "Select FormName from MenuMaster Where MenuText = '" +sender.ToString + "'";
 
if (sMenuRD.HasRows) {
sMenuRD.Read();
frmName = sMenuRD(0).ToString;
DynamicallyLoadedObject(frmName).Show(this);
}
else {
Interaction.MsgBox("Under Construction", MsgBoxStyle.Exclamation, "Technical Error");
}
 

}
GeneralProblem in DynamicallyLoadedObject()memberArul Soosai12 Apr '09 - 21:07 
Hi,
 
i got the correct formname in objectName(as string)DynamicallyLoadedObject()when i debug
but i face the problem in Dim Type as Type = System.Reflection(GetAssesmbly(--------)
 
Here the system return that returnObj is nothing
 
then i getting this error message --
Object reference not set to an instance of an object.
 
Please help me
GeneralRe: Problem in DynamicallyLoadedObject()memberArul Soosai12 Apr '09 - 21:32 
Hi All,
 
I solved this issue
Thanks
GeneralRe: Problem in DynamicallyLoadedObject()memberBad Programmer13 Apr '09 - 1:03 
Confused | :confused: Can u post the solution for others interest as well.
 
Thanks,
Bad Programmer
 
Bad Programmer

GeneralRe: Problem in SelectedchildMenu_OnClick eventmemberArul Soosai14 Apr '09 - 22:00 
Hi All,
 
if i click child menu is " Exit" how to change the code SelectedChildMenu_OnClick event
=========================================
If sMenuRD.HasRows Then
sMenuRD.Read()
frmName = sMenuRD(0).ToString()
DynamicallyLoadedObject(frmName).Show(Me)
 
========================
 
I need to close the application when i click child menu " Exit" (parent menu is "File")
 
Please advise
GeneralRe: Problem in SelectedchildMenu_OnClick eventmemberBad Programmer18 Apr '09 - 18:27 
hey create a form named frmExit. call 'Exit' method during Page_Init.
 
Thanks,
Bad Programmer
 
Bad Programmer

GeneralRe: Problem in DynamicallyLoadedObject()memberAlicealiciasawarak28 Mar '11 - 18:38 
Arul,
 
Can you provide the solution? I also got this message "Object reference not set to an instance of an object."
 
Your help is much appreciated.
GeneralRe: Problem in DynamicallyLoadedObject()memberAlicealiciasawarak30 Mar '11 - 20:55 
Can you please share your solution. I also facing the same problem, and my form name is correct, and the form also is in the project.
 
Please do assist and help.
QuestionDynamic Creation of MenuStrip- C#.net [modified]memberShahid K5 Mar '09 - 1:24 
I have Four Tables, and according to Roles provided Menus are goinng to be rendered in Windows Application using C#.net VS 2005
 
Table1: MNU_MASTER
 
MENU_ID int Unchecked
PARENTID numeric(38, 0) Checked
MENU_NAME varchar(150) Checked
SEQNO numeric(38, 0) Unchecked

Table2: MNU_FUNCTION
 
MNU_ID int Checked
PATH varchar(150) Checked
 
Table3: MNU_ROLE_PROFILE
 
Role_ID int Unchecked
Menu_ID int Unchecked
 
Table4:MNU_ROLE_MASTER
 
ROLE_ID int Unchecked
ROLE_NAME varchar(150) Checked
 

Thanks In advance.
 
modified on Thursday, March 5, 2009 7:47 AM

GeneralResult listed by vertical, not horizontalmemberHendra Prasetyo15 Jan '09 - 16:59 
I had try this code, but the result was not correct. Because the main menu listed by vertical, not horizontal. Can Anybody help me ?
 
Layout result :
---------------
MASTER
- USER
- SUPPLIER
TRANSACTION
- PURCHASE
 
I want the result :
--------------------
MASTER TRANSACTION
- User - Purchase
- SUPPLIER
 
Thanks
AnswerRe: Result listed by vertical, not horizontalmemberBad Programmer15 Jan '09 - 20:51 
Hi,
 
Do this,
 
Set the MainMenuID of Purchase to User's MenuID
Revert if it still creates problem
 
Thanks
 
Bad Programmer

Generalopen dynamic form in MDI windowmemberMithuya4 Nov '08 - 8:05 
I want to open this dynamic form in MDIwondow but it is not working,
just I have used before opening the form and also my parent window is MDI, it is working fine for the hard coded form name.
 
DynamicallyLoadedObject(frmName).MdiParent = Me
 
Please help.
GeneralRe: open dynamic form in MDI windowmemberBad Programmer5 Nov '08 - 1:13 
Hi,
 
try this in DynamicallyLoadedObject
 
Type = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("root_name.frmName")
 
Revert if u still hav this error
 
Thanks,
Bala
 
Bad Programmer

GeneralRe: open dynamic form in MDI windowmemberMark Denson16 Nov '09 - 7:01 
Try the following modifications:
 
Private Sub SelectedChildMenu_OnClick(ByVal sender As Object,
ByVal e As System.EventArgs)
Dim Conn As New Conn1
Dim sMenuRD As SqlClient.SqlDataReader
Dim frmName As String = ""
Dim frm As New Form
sQry = ""
sQry = "Select FormName from MenuMaster Where MenuText = '" &
sender.ToString & "'"
sMenuRD = Conn.ReaderData(sQry)
If sMenuRD.HasRows Then
sMenuRD.Read()
frmName = sMenuRD(0).ToString
' DynamicallyLoadedObject(frmName).Show(Me)
'Changes to set form as a child of the parent form:
frm = DynamicallyLoadedObject(frmName)
frm.MdiParent = Me
frm.show()
'End changes
Else
MsgBox("Under Construction", MsgBoxStyle.Exclamation, "Technical Error")
End If
sMenuRD.Close()
End Sub
GeneralRe: open dynamic form in MDI windowmemberFinder11511 Jun '11 - 21:10 
Hi,
 
I can't using the way:
-------------------------------------
frm = DynamicallyLoadedObject(frmName)
frm.MdiParent = Me
frm.show()
-------------------------------------
because I put my code in a new class, so how can i do?
my class:
-------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XRDataAccess;
using MySql.Data.MySqlClient;
using System.Reflection;
 
namespace QLTN
{
class CreateMenu
{
MenuStrip _menuQLTN;
 
public MenuStrip MenuQLTN
{
get { return _menuQLTN; }
set { _menuQLTN = value; }
}
 
public CreateMenu()
{
MySqlDataReader mnRD;
DataAccessLayer dal = new DataAccessLayer();
mnRD = dal.ReaderData("select * from tblmenu where mainmenuid=0");
MenuQLTN = new MenuStrip();
if (mnRD.HasRows)
{
while (mnRD.Read())
{
MenuQLTN.Items.Add(Convert.ToString(mnRD[1]), null, new System.EventHandler(MainMenu_OnClick));
}
}
}
private void MainMenu_OnClick(object sender,EventArgs e)
{
int i;
ContextMenuStrip cms = new ContextMenuStrip();
ToolStripMenuItem tsi = new ToolStripMenuItem();
string[] sMenu = null;
int parentMenuID = 0;
MySqlDataReader sMenuRD;
DataAccessLayer dal = new DataAccessLayer();
sMenuRD = dal.ReaderData("select menuid from tblmenu where menutext='" + sender.ToString() + "'");
if (sMenuRD.HasRows)
{
sMenuRD.Read();
parentMenuID = (int)sMenuRD["menuid"];
}
sMenuRD.Close();
sMenuRD = dal.ReaderData("select * from tblmenu where mainmenuid='" + parentMenuID + "' Order BY menuorder");
Array.Resize(ref sMenu, 1);
if (sMenuRD.HasRows)
{
Array.Resize(ref sMenu, 1);
i = 0;
while (sMenuRD.Read())
{
Array.Resize(ref sMenu, i + 1);
sMenu[i] = sMenuRD["menutext"].ToString();
i++;
}
}
sMenuRD.Close();
foreach (string sMn in sMenu)
{
cms.Items.Add(sMn, null, new System.EventHandler(SelectedChildMenu_OnClick));
}
tsi = (ToolStripMenuItem)sender;
tsi.DropDown = cms;
tsi.ShowDropDown();
}
private void SelectedChildMenu_OnClick(object sender, EventArgs e)
{
string frmName;
Form f=new Form();
DataAccessLayer dal = new DataAccessLayer();
MySqlDataReader sMenuRD = dal.ReaderData("select formname from tblmenu where menutext='" + sender.ToString() + "'");
if (sMenuRD.HasRows)
{
sMenuRD.Read();
frmName = sMenuRD[0].ToString();
DynamicallyLoadedObject(frmName).Show();
}
}
private Form DynamicallyLoadedObject(string objectName, object[] args = null)
{
object returnObj = null;
Type Type = Assembly.GetExecutingAssembly().GetType("QLTN." + objectName);
//Type Type = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("QLTN." + objectName);
if (Type != null)
{
returnObj = Activator.CreateInstance(Type, args);
}
return (Form)returnObj;
}
}
}
GeneralRe: open dynamic form in MDI windowmemberFinder11511 Jun '11 - 20:51 
Hi,
I've got an error:
Error 1 Cannot implicitly convert type 'object' to 'System.Type'. An explicit conversion exists (are you missing a cast?) D:\Develop\QLTN\QLTN\CreateMenu.cs
 
How to fix it?
 
private Form DynamicallyLoadedObject(string objectName, object[] args = null)
{
object returnObj = null;
//Type Type = Assembly.GetExecutingAssembly().GetType("QLTN." + objectName);
Type Type = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("QLTN." + objectName);
if (Type != null)
{
returnObj = Activator.CreateInstance(Type, args);
}
return (Form)returnObj;
}
GeneralExcelentmemberlefaconi25 Oct '08 - 5:06 
This sample is very good,
 
Thanks
GeneralRe: ExcelentmemberMithuya4 Nov '08 - 8:04 
I want to open this dynamic form in MDIwondow but it is not working,
just I have used before opening the form and also my parent window is MDI, it is working fine for the hard coded form name.
 
DynamicallyLoadedObject(frmName).MdiParent = Me
 
Please help.
GeneralSimple superbmemberashu fouzdar26 Aug '08 - 20:43 
Congrats !!!, Nice and innovative idea.
 
Please keep it going on, and thanks for sharing. Smile | :)
 
dnpro
"Very bad programmer"

GeneralDownload codememberbkresimir25 Feb '08 - 19:30 
Please where I can download a source code
 
Thanks !! Smile | :)
QuestionHacking Access databasememberGyanendra kumar thakur29 Jun '07 - 19:07 
I have a access database without password created by previous employee I have to use it but it is password protected.
Can any body help me to solve this problem????
 
all the best

AnswerRe: Hacking Access databasememberBala J30 Jun '07 - 9:43 
HI,
Try this link and download the tool "Access Password v10.1.6805"
 
http://lastbit.com/access/[^]
QuestionUse the 'new' keyword to create an object instance.memberkeonj26 Jun '07 - 12:00 
Hi,
 
Your code is looking great. But i'm having only one problem.
 
I'm trying to use your code in a form with a MdiContainer. When i click in the menu on a dynamic created menuItem it return following error: "Use the 'new' keyword to create an object instance."
 
Properly there is a error in the DynamicallyLoadedObject. But i can't find a solution to solve this. Can you help me out?
 
Thanks in advanced
Koen
AnswerRe: Use the 'new' keyword to create an object instance.memberBala J30 Jun '07 - 11:17 
Hi,
Follow these steps:
1. Add a MDIparentForm to ur project.
2. Remove the default "ToolStrip" and "Menu Strip"
3. Now add a new instance of "Menu Strip" in design mode

Now u wont face any problem
 

GeneralRe: Use the 'new' keyword to create an object instance.memberDustin Klinkenberg20 Aug '08 - 7:53 
don't see how that helps... had exactly the same prob - after a couple of hours of swearing i figured out you need the root namespace not the assembly name - there's an underscore instead of a space compared:
 
Type = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("root_name.frmName")
 
Dead | X|
GeneralRe: Use the 'new' keyword to create an object instance.memberAlicealiciasawarak28 Mar '11 - 19:00 
I still got the message after I have change the
Dim Type As Type = Assembly.GetExecutingAssembly().GetType("[MENU]." & objectName) to
Dim Type As Type = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("root_name.frmName")
 
Please assist on this.
GeneralCreate a Connection classmemberGeertD19 Jun '07 - 0:52 
Hi,
Nice article....but something is missing I think...
 
You say "Create a connection class....See article for connection class: #"....But I don't see it (even when I ware my glasses Laugh | :laugh: )
 
The reason I asked this, is not because I couldn't create one (or to work fast, I could even put the code in the example), but in your code I saw a line "IUserAccesMode = Globalvalues.IuserAccess.Text" and some other strange things. So could you please post the full solution (or at least all the necessary classes to build the project myself ??)
 
Thnx in advance
Geert
GeneralRe: Create a Connection classmemberBad Programmer5 Nov '08 - 1:22 
apologize for long delay.
 
please dont use the below class, i created this at the start of my carrer and it has lot of issues.
 
Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.SqlClient
Public Class Conn1
Private oConn As SqlConnection
Private oCommand As New SqlCommand
Private oReader As SqlDataReader
Private oDataAdapder As New SqlDataAdapter
Private inCommand As New SqlCommand
Private connstring As String = Nothing
'openconnection
Public Sub openconnection()
Try
If connstring Is Nothing Then
connstring = ReadConnectionString()
End If
oConn = New SqlConnection(connstring)
If oConn.State = ConnectionState.Open Then
oConn.Close()
End If
oConn.Open()
Catch Ex As Exception
Dim uObj As New BasicFunctions
uObj.logoutAgent()
'Throw New System.Exception("Error Source: Connection " + Ex.Message)
End Try
End Sub 'openconnection
' Close Connection
Private Sub closeconnection()
Try
If oConn.State = ConnectionState.Open Then
oConn.Close()
oConn = Nothing
End If
Catch Ex As Exception
'Throw New System.Exception("Error Source: Connection " + Ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
End Try
End Sub 'closeconnection
'Read Connection String
Private Function ReadConnectionString() As String
connstring = "Data Source=;Initial Catalog=;User Id=;Password=;"
Return connstring
End Function
'DataReader with a select statement3
Public Function ReaderData(ByVal mySelectQuery As String) As SqlDataReader
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(mySelectQuery, oConn)
oCommand.CommandTimeout = 90
'oReader = oCommand.ExecuteReader(CommandBehavior.CloseConnection)
oReader = oCommand.ExecuteReader
Return oReader
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + mySelectQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
End Try 'myReader = null;
End Function 'ReaderData
'Insert routine
Public Function Insert(ByVal myInsertQuery As String) As Object
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(myInsertQuery, oConn)
oCommand.CommandTimeout = 90
oCommand.ExecuteNonQuery()
'oReader = oCommand.ExecuteReader(CommandBehavior.CloseConnection)
Return "0"
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + myInsertQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
'oCommand = Nothing
'oConn = Nothing
End Try 'myReader = null;
End Function
'Insert routine With Identity fetching
Public Function Insert(ByVal myInsertQuery As String, ByVal strPar As String) As Integer
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(myInsertQuery, oConn)
oCommand.Parameters.Add(New SqlParameter("@SrID", SqlDbType.Int))
oCommand.Parameters("@SrID").Direction = ParameterDirection.Output
oCommand.Parameters("@SrID").SourceColumn = strPar
oCommand.CommandTimeout = 90
Return Convert.ToInt16(oCommand.ExecuteScalar)
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + myInsertQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
oConn = Nothing
End Try 'myReader = null;
End Function
'Execute routine
Public Function ExScalar(ByVal myInsertQuery As String) As String
Try
Dim objcon As Object = oConn
Dim strResult As String
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(myInsertQuery, oConn)
oCommand.CommandTimeout = 90
strResult = oCommand.ExecuteScalar().ToString
Return strResult
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + myInsertQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
oConn = Nothing
End Try 'myReader = null;
End Function
'Fill DataTable
Public Function FillSPDataTable(ByVal MySelectQuery As String) As DataTable
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(MySelectQuery, oConn)
Dim MyDataTable As New DataTable
oDataAdapder = New SqlDataAdapter(oCommand)
oCommand.CommandTimeout = 300
oCommand.CommandType = CommandType.StoredProcedure
oDataAdapder.Fill(MyDataTable)
Return MyDataTable
Catch ex As Exception
'Throw New System.Exception(ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
closeconnection()
End Try
End Function
'Fill DataTable
Public Function FillDataTable(ByVal MySelectQuery As String) As DataTable
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(MySelectQuery, oConn)
Dim MyDataTable As New DataTable
oDataAdapder = New SqlDataAdapter(oCommand)
oCommand.CommandTimeout = 300
oCommand.CommandType = CommandType.Text
oDataAdapder.Fill(MyDataTable)
Return MyDataTable
Catch ex As Exception
'Throw New System.Exception(ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
closeconnection()
End Try
End Function
'Fill Dataset
Public Function FillDataSet(ByVal MySelectQuery As String) As DataSet
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(MySelectQuery, oConn)
Dim MyDataSet As New DataSet
oDataAdapder = New SqlDataAdapter(oCommand)
oCommand.CommandTimeout = 300
oCommand.CommandType = CommandType.Text
oDataAdapder.Fill(MyDataSet, "myTable")
Return MyDataSet
Catch ex As Exception
'Throw New System.Exception(ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
closeconnection()
End Try
End Function
End Class
 
Bad Programmer

QuestionRe: Create a Connection classmemberGeertD5 Nov '08 - 1:49 
Hi,
 
you say: "...please dont use the below class, i created this at the start of my carrer and it has lot of issues...", any suggestions how you would now as an experienced programmer Wink | ;) , write that class ? or could you at least shed a light on the issues you mention ?
 
Greetz
 
Geert D.
AnswerRe: Create a Connection classmemberBad Programmer5 Nov '08 - 19:47 
Hi,
 
I was using SQLHelper.cs provided by microsoft. Any more questions Poke tongue | ;-P
 
Thanks,
Bala
 
Bad Programmer

GeneralArticle missing picmemberJared James Sullivan17 Jun '07 - 16:29 
Hi,
 
Should always include pic with your articles, so users know instantly what it is about.
GeneralRe: Article missing picmemberBala_se18 Jun '07 - 10:20 
HI,
i tried to attach a pic, but i couldnt. so i added as an attachment

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 24 Aug 2008
Article Copyright 2007 by Bad Programmer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid