Hello:
In my MDIParent I have a good SQLConnection and I would like to open the same database in the MDIChild without re-opening it. Can someone tell me how?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
theLizardPosted Mar 11, 2010, 3:44 AM
You MUST be diligent in this unless for some obscure reason that you need to manage connection outside of SQL Servers default pools.
using System;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
//example only should not be in sqlCon class.
public class app_user
{
public string name;
public string pwd;
public string whatever;
public void app_user()
{
}
}
public class sqlCon
{
public SqlConnection con = null;
public SqlDataReader reader = null;
public SqlCommand cmd = null;
public SqlParameter Param = null;
public sqlCon()
{
cmd = new SqlCommand();
Param = new SqlParameter();
}
//-----------------------------------------------------------------
public void addParam(SqlParameter param)
{
}
//-----------------------------------------------------------------
public void connect()
{
System.Configuration.AppSettingsReader asr = new System.Configuration.AppSettingsReader();
con = new SqlConnection((string)asr.GetValue("TheConnectionString", typeof(string)));
con.Open();
//con.GetSchema(); this is used if you want to dynamically load grid view cells based on data type
}
//-----------------------------------------------------------------
private static SqlDataAdapter DataAdapter(String sqlString)
{
// Assuming all the default settings, create a SqlDataAdapter working
// current database in SQL Server.
System.Configuration.AppSettingsReader asr = new System.Configuration.AppSettingsReader();
return new SqlDataAdapter(sqlString, (string)asr.GetValue("TheConnectionString", typeof(string)));
// I do not use one but you can
}
//-----------------------------------------------------------------
public string get(string field)
{
return reader[field].ToString();
}
//-----------------------------------------------------------------
public bool getBoolean(string field)
{
return ((bool)(int.Parse(reader[field].ToString()) == 1 ? true : false));
}
//-----------------------------------------------------------------
public void ExecuteReader()
{
reader = cmd.ExecuteReader();
}
//-----------------------------------------------------------------
public SqlDataReader ExecReader()
{
return (cmd.ExecuteReader());
}
///
///
///
//-----------------------------------------------------------------
public void write()
{
cmd.ExecuteNonQuery();
}
//-----------------------------------------------------------------
public bool read()
{
return reader.Read();
}
//-----------------------------------------------------------------
public void command(String s)
{
cmd.Connection = con;
cmd.CommandText = s;
}
//-----------------------------------------------------------------
public void terminate()
{
try
{
if (reader != null)
{
reader.Close();
reader.Dispose();
}
}
catch (Exception err)
{
}
try
{
if (cmd != null)
{
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}
catch (Exception err)
{
}
try
{
if (con != null)
{
con.Close();
con.Dispose();
}
}
catch (Exception err)
{
}
}
//-----------------------------------------------------------------
public void beginTrans()
{
cmd.Transaction = con.BeginTransaction();
}
//-----------------------------------------------------------------
public void commitTrans()
{
cmd.Transaction.Commit();
}
//-----------------------------------------------------------------
public void rollbackTrans()
{
try
{
if (cmd != null)
cmd.Transaction.Rollback();
}
catch (Exception err)
{
}
}
//-----------------------------------------------------------------
public string getFieldValue(string s, string field)
{
//usage con.getFieldValue("SELECT * FROM user WHERE name = 'bob'", "emailAddress")
//this example usage will return the email address from database table.
string fieldValue = "";
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if (con.read())
{
fieldValue = con.get(field).ToString();
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return (fieldValue);
}
//-----------------------------------------------------------------
public bool getFieldBool(string s, string field)
{
bool fieldValue = false;
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if (con.read())
{
fieldValue = con.getBoolean(field);
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return (fieldValue);
}
//-----------------------------------------------------------------
public bool findDuplicate(string s)
{
//usage con.findDuplicate("SELECT * FROM user WHERE name = 'bob" AND email = '[email protected]'")
//build the sql string any way you want.
bool found = false;
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if (con.read())
{
found = true;
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return (found);
}
//--------------------------------------------------------------
public bool getDuplicateValue(string table, string field, string value)
{
bool found = false;
string s = "SELECT * FROM " + table + " WHERE " + field + " = @value";
sqlCon con = new sqlCon();
//how to add parameters
con.cmd.Parameters.AddWithValue("value", value);
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if (con.read())
{
found = true;
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return (found);
}
//-----------------------------------------------------------------
public bool execSQL(string s)
{
bool success = true;
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.beginTrans();
con.write();
con.commitTrans();
}
catch (Exception err)
{
con.rollbackTrans();
success = false;
}
finally
{
con.terminate();
}
return (success);
}
//-----------------------------------------------------------------
public bool execSQL(sqlCon con, string s)
{
//an override with an sqlCon being sent rather than instantiating a new connection.
bool success = true;
try
{
con.connect();
con.command(s);
con.beginTrans();
con.write();
con.commitTrans();
}
catch (Exception err)
{
con.rollbackTrans();
success = false;
}
finally
{
con.terminate();
}
return (success);
}
//-----------------------------------------------------------------
public int getCount(string s)
{
// usage getCount("SELECT COUNT(whatever) as count FROM table [where]")
int count = 0;
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if (con.read())
count = int.Parse( con.get("count"));
}
catch (Exception err)
{
count = 0;
}
finally
{
con.terminate();
}
return (count);
}
//-----------------------------------------------------------------
public void loadDropDown(ComboBox cb, string s, string fieldName)
{
sqlCon con = new sqlCon();
int count = 0;
try
{
con.connect();
con.command(s);
con.ExecuteReader();
while (con.read())
{
cb.Items.Add(con.get(fieldName));
}
}
catch (Exception err)
{
//do what ever is needed
}
finally
{
con.terminate();
}
return(ids);
}
//-----------------------------------------------------------------
public void loadCheckList(CheckBoxList l, string s, string fieldName)
{
sqlCon con = new sqlCon();
l.Items.Clear();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
while (con.read())
{
l.Items.Add(con.get("fieldName"));
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
}
//-----------------------------------------------------------------
public void getUser(string s, app_user user)
{
//usage con.getUser("SELECT * FROM user WHERE user_id = id", user);
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if(con.read())
{
user.name = get("name");
user.whatever = get("whatever");
//any other field you want.
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
//at this point the app_user class is filled with all necessary details and will be available for you to use on return to calling point
}
//-----------------------------------------------------------------
public bool userExists(string s)
{
//usage con.userExists("SELECT * FROM user WHERE name = 'whatever'");
bool userExists = false;
try
{
con.connect();
con.command(s);
con.ExecuteReader();
if(con.read()) //if it reads one, the user exists, however you would use more than one field to determine this.
{
userExists = true;
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return(userExists);
}
//-----------------------------------------------------------------
/* I have left this here simply to demonstrate that these methods can be used in forms and web scenarios.
* make sure to add web referances if used for web.
*
public string loadMainMenu(Page p, string s)
{
session headings = (session)p.Session["headings"];
string html = "", mnuName;
string id = "";
long count=0;
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
while (con.read())
{
count=0;
mnuName = con.get("heading");
id = con.get("id");
html += "
html += mnuName;
html += "
//html += loadSubMainMenu(p, "SELECT * FROM menuGroup WHERE headingId = " + id + " ORDER BY groupHeading", id);
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return (html);
}
//-----------------------------------------------------------------
public string loadSubMainMenu(Page p, string s, string hid)
{
session headings = (session)p.Session["headings"];
string html = "", mnuName;
string id = "";
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.ExecuteReader();
while (con.read())
{
mnuName = " > " + con.get("groupHeading");
id = con.get("id");
html += "
html += mnuName;
html += "
}
}
catch (Exception err)
{
}
finally
{
con.terminate();
}
return (html);
}
*/
}
GustavoPosted Mar 11, 2010, 9:37 AM
This post is getting too long. I am going to accept it and read the code submitted and try to figure it out. Then is I have issues with parts, I will just post on the specific parts in seperate posts.
Thanks
Sam HobbsPosted Mar 11, 2010, 2:17 AM
All you had to do is to change "public static OpenDB" to "public static void OpenDB". Please get a good book about C#. You really need to learn the basics such as that. You need to learn about classes.
Sam HobbsPosted Mar 11, 2010, 2:09 AM
theLizardPosted Mar 11, 2010, 12:41 AM
eg.
you can have
public string connect(string DBServer, string DBDatabase, string DBLogin_ID, string DBPassword)
{
string conStr = @"Server=" + DBServer + "; Database=" + DBDatabase + "; User ID=" + DBLogin_ID + "; Password=" + DBPassword + ";";
con = new SqlConnection(conStr);
}
Or you can send the whole connection string in one hit or get the connection string from a config file.
If you will only have one connection string then it is safe to put it into the class itself but my preferred method is in a config file so that you can have more than one connection string depending on how many servers you need to connect with
Generally all that I do when I need to connect is to instantiate a new sqlCon wherever I need to then close it after using it, it really is a very efficient way of doing things.
If you get your connection string from a config file all you then need to do is
sqlCon = new sqlCon();
con.connect();
do what you need to do here because at this point you have access to ALL the properties, methods and events of the connection type weather it be ODBC, MySql or SqlConnection. The amount of code you write here depends on any worker classes that you have created or any in-line code you write between connect and terminate.
con.terminate();
GustavoPosted Mar 10, 2010, 11:08 PM
Well, I put the code in and used my own variables.
I have a question... repeated question: The following code, does it go into the class ot main program? I think it shlould be in the main program, but I understood that all the code is in the class. (I am wrong?)
string conStr = @"Server=" + DBServer + ";"
+ "Database=" + DBDatabase + ";"
+ "User ID=" + DBLogin_ID + ";"
+ "Password=" + DBPassword + ";";
sqlCon = new sqlCon(); //instantiate
con.connect(constr); //connect
GustavoPosted Mar 10, 2010, 10:15 PM
In am sort of understanding it. Right now I am changing my code to be your last code sample. Hopefully soon I will see if it works. When I get it to work, I will then read your next post.
I really appreciate your help. I learned a lot today.
theLizardPosted Mar 10, 2010, 10:07 PM
None of the code would be in your main form, it should not be anyway.
If I want to populate a bunch of object in the form
This depends on what the bunch of objects are, if you are talking about the objects being the fields of a record and these are represented as text boxes then you would have worker classes that manage these for you.
as far as accessing the data, the class is just there to help you access your database, it can have functions to fill objects but I would keep these separate from the database management class put them in worker classes.
one worker class could have all the functions to fill lists boxes, combo boxes, tree views whatever.
as I said before to fill list type objects the worker class would not care who owns the object, just fill it, you do not need to return the object from the worker either.
if in your main form you want to load a combo box of user names you would simply call the worker class like this
worker.fillCombo(cbUser, commandText, fieldName);
in this case cbUser is the combo box, because you have sent a reference, whatever is done to the combo box you sent in the worker function affects the object on the main form so if worker adds items, these items will appear in the combo box on the main form, do you understand?
this is another example from a fill list box object
fillL(ComboBox cb, string commandText, string fieldName);
{
sqlCon = new sqlCon();
con.connect();
con.CommandText = commandText;
while (sqlCon.read())
{
cb.Items.Add(sq.get(fieldName));
}
sqlCon.terminate();
}
GustavoPosted Mar 10, 2010, 8:59 PM
Thanks for the sample. I will study it. Just a few little question.
1) The code you just sent would be the class only? None of the code would be in the main (calling) program?
2) If I want to populate a bunch of object in the form, would I have to do it in the class or the main program? If in the main program, how do I access the data from the class?
Sorry for being such a pest. I am getting this stuff, slowly but surely.
theLizardPosted Mar 10, 2010, 8:32 PM
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public class sqlCon
{
public SqlConnection con = null;
public SqlDataReader reader = null;
public SqlCommand cmd = null;
public SqlParameter Param = null;
public string[] fieldDefs;
public sqlCon()
{
cmd = new SqlCommand();
Param = new SqlParameter();
}
//-----------------------------------------------------------------
public void addParam(SqlParameter param)
{
}
//-----------------------------------------------------------------
public void connect(string connectionString)
{
con = new SqlConnection(connectionString = (your connection string));
con.Open();
con.GetSchema();
}
//-----------------------------------------------------------------
}
string conStr = @"Server=" + DBServer + ";"
+ "Database=" + DBDatabase + ";"
+ "User ID=" + DBLogin_ID + ";"
+ "Password=" + DBPassword + ";";
sqlCon = new sqlCon(); //instantiate
con.connect(constr); //connect
use it.
con.CommandText = "INSERT INTO table ...)
or create functions
con.execSQL("INSERT INTO table ...")
//-----------------------------------------------------------------
public bool execSQL(string s)
{
bool success = true;
sqlCon con = new sqlCon();
try
{
con.connect();
con.command(s);
con.beginTrans();
con.write();
con.commitTrans();
}
catch (Exception err)
{
con.rollbackTrans();
success = false;
}
finally
{
con.terminate();
}
return (success);
}
//---------------------------------------
here is a start, but you need to work out what to do.
GustavoPosted Mar 10, 2010, 8:17 PM
This is the code that I have in my main program. I have a button that when clicked it suppose to load the grid.
The ClassDB.Test() is just for test use only. I just want to be sure I was going there.
The ClassDb.OpenDB, I guess it works, I dont get any errors and I do see the messagebox that it got there.
However, The line: SqlDataAdapter TestDataAdapter = new SqlDataAdapter(SQLSelect, IPConnection); <<
public void buttonClassDB_Click(object sender, EventArgs e)
{
ClassDB.Test();
ClassDB.OpenDB(DBServer, DBDatabase, DBLogin_ID, DBPassword);
//
SQLSelect = "SELECT * FROM [User]"
+ " WHERE [User_ID] = '" + textBoxLoginUser_ID.Text + "'"
+ " AND"
+ " [Status_ID] = '1'"
+ " AND"
+ " Password = '" + textBoxLoginPassword.Text + "'";
//
SqlDataAdapter TestDataAdapter = new SqlDataAdapter(SQLSelect, IPConnection);
DataSet TestDataSet = new DataSet();
//
TestDataAdapter.Fill(TestDataSet);
dataGridViewGrid.DataSource = TestDataSet.Tables[0];
dataGridViewGrid.Refresh();
}
GustavoPosted Mar 10, 2010, 7:55 PM
Ok, its good that its not the Visul Studio tool.
I did try to create a seperate class, but I cant get it to work.
This is the class that I wrote. What do you think? Am I doing it wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//=====================================================
// Added because it was not included in original class.
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using System.Reflection;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
//=====================================================
namespace ICEPack
{
public partial class ClassDB
{
public void OpenDB(string DBServer, string DBDatabase, string DBLogin_ID, string DBPassword)
{
MessageBox.Show(DBServer + ", " + DBDatabase + ", " + DBLogin_ID + ", " + DBPassword + "...");
SqlConnection IPConnection = new SqlConnection();
IPConnection.ConnectionString =
@"Server=" + DBServer + ";"
+ "Database=" + DBDatabase + ";"
+ "User ID=" + DBLogin_ID + ";"
+ "Password=" + DBPassword + ";";
IPConnection.Open();
//return ;
}
public void Test()
{
MessageBox.Show("I am here, in ClassDB.Test...");
}
}
}
theLizardPosted Mar 10, 2010, 7:48 PM
This is a case where one shoe fits all.
When you deal with direct connections you eliminate any need for data sets in the Visual Studio sense, you can completely ignore any need for binding anything to anything you are in control.
You can create worker classes that will load any control on any of your forms, these worker classes could also be used in any other application along with the database class that you may write in the future.
You development cycle would be improved no end.
I have written database classes that loads grids and tree views without me specifically telling the grid what type of cell data type it needed to load, all this is available for dynamic control using the GetSchema() method of whichever connection type you use.
The main reason people use data bound controls is that they do not need to know the inner workings of SQL so it becomes simple to work with but this type of simplicity comes at a cost, the cost is less control over what you want or need to do.
This is the main reason we have question like the one's that you are asking, to me, loading a tree or grid with what I want is a ten minute operation, I can load tree views and attach a grid to any the node of the tree view in about 11 minutes.
All this is because I created the classes that I needed about 5 years ago, they are still relevant today as they were then, they will work in the next version of Visual Studio and the next with little to no modifications.
To enhance my database classes I also created new controls inherited from standard controls where I can assign record numbers to each tree node or grid row or list box item so that if I need to get the full record for a list box item it is as simple as issueing a frmUserForm.loadRecord(listbox1.dbRecord)
GustavoPosted Mar 10, 2010, 7:01 PM
About the "database management class"... Are you talking about the tool in Visual Studio to set up a DataSet? If so, it allows me to connect to the database, but I want to define the server, database, user and password, when I login to my program. I dont see how I can change the DataSet properties. OR, am I still wrong?
GustavoPosted Mar 10, 2010, 6:25 PM
This is my current code to open the database. Is this the wrong way?
DBServer = textBoxLoginProfileServer.Text;
DBDatabase = textBoxLoginProfileDatabase.Text;
DBLogin_ID = textBoxLoginProfileLogin_ID.Text;
DBPassword = textBoxLoginProfilePassword.Text;
SqlConnection IPConnection = new SqlConnection();
IPConnection.ConnectionString =
@"Server=" + DBServer + ";"
+ "Database=" + DBDatabase + ";"
+ "User ID=" + DBLogin_ID + ";"
+ "Password=" + DBPassword + ";";
IPConnection.Open();
//
SQLSelect = "SELECT * FROM [Menu]"
+ " FULL JOIN Program"
+ " ON Menu.Menu_ID = Program.Program_ID"
+ " WHERE Menu.Status_ID = '1'"
+ " ORDER BY Menu.Level_1, Menu.Level_2, Menu.Level_3, Menu.Level_4, Menu.Level_5";
SqlDataAdapter MenuDataAdapter = new SqlDataAdapter(SQLSelect, IPConnection);
DataSet TestDataSet = new DataSet();
//
MenuDataAdapter.Fill(TestDataSet);
dataGridViewGrid.DataSource = TestDataSet.Tables[0];
dataGridViewGrid.Refresh();
IPConnection.Close();
GustavoPosted Mar 10, 2010, 6:18 PM
Ok... I will go look at the old posts, where you told me how to" create a database management class ". I dont remember that one... but I will look for it.
theLizardPosted Mar 10, 2010, 6:01 PM
SQL Server handles connection pools for you.
And I have already given you examples, you need to create a database management class to do these things for you.
The database management class CAN be used to fill List boxes anything you just need to handle them.
The database class does NOT need to care who owns the List box just what to load it with.
public void LoadMyListBox(ListBox l, string sql, string fieldName)
{
con.CommandText = sql;
while(con,read())
{
lb.Items.Add(con.get(field));
}
con.terminate();
}
This example, would fill a list box from anywhere in your application, the listbox you send would be filled with what you want
you would call it from any child form with this
sqlCon = new sqlCon();
con.LoadMyListBox(lbUser, "SELECT * FROM user","userName");
filling GridViews, TreeViews any control is just as easy, all you need to do is build the framework to make it easy this takes a little time but you do it once and is available to you in ANY of your applications.
GustavoPosted Mar 10, 2010, 5:32 PM
I see your point.. .Lets say I will open, get and close database.
However: The code for opening the database, I would like to have in one place only, instead of having it in each form.
If I want to do a select to a different table in a later point in the operation/program... How do I re-open the connection? How do I go to the class to open it?
theLizardPosted Mar 10, 2010, 5:18 PM
This is precisely the reason you
open
get
and
close
the connection should NOT be open any longer than it takes an sql statement to execute, this is why you need to implement begin transaction, commit transaction or rollback transaction on ANY error, especially where there are multiple tables affected by a single transaction. THIS IS PROPER DATABASE MANAGEMENT
in my class for sql management I do this
string mysqlstatement = "INSERT INTO table(a,b,c,d) values(@a,b,c,d)"; //get this any way you want.
sqlCon con = new sqlCon()
//if you want to use parameters, and you should,
// con.Parameters.AddWithValues("a", a);
con.execsql(mysqlstatement)
con.terminate();
these 3 lines can insert, update or delete records.
You need to sit down and do one thing at a time, you are jumping all over the place trying to do all things at once, you are confusing yourself and repeating questions.
GustavoPosted Mar 10, 2010, 4:39 PM
I have tried to create/write a class, but it gives me an error. I have been sufing all day (6+ hours) trying to find some samples of how to get back the database connection.
About opening the database, get what I need and close it...??? What if someone else opens the database and chnages it. I want to write this application for a multi-user system. I might be wrong, but I am trying.
theLizardPosted Mar 10, 2010, 4:32 PM
Lead me to where I should find this."
I have been trying to lead you to the proper class ever since you started posting, the class that hirendra suggested is the class I have been talking about for some time and have given examples for, except that it does NOT need to be a static class.
and you do NOT want to keep a connection open any more than the time needed to get the data, pupolate whatever and close it, you will be asking for troubles otherwise since you are not that experienced at this type of work and do not yet know the pitfalls.
Good luck with what you are trying to do, this is the last post to your questions I will make as you seem not to know which direction you want to go in and you have more than an adequate supply of willing advisers.
GustavoPosted Mar 10, 2010, 4:25 PM
BTW: I did try to put it in a class. But it still gave me errors. If I create new class, how to I have it send back the database connection so I can do the SQLSelect on it?
GustavoPosted Mar 10, 2010, 4:19 PM
Here is the code of the Program.cs. It gives me an error at: public static OpenDB(string DBServer, string DBDatabase, string DBLogin_ID, string DBPassword)
It says "Method must have a return type".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
//=====================================
// Added
//using System;
//using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
//using System.Windows.Forms;
using System.Reflection;
using System.Drawing.Printing;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
//=====================================
namespace ICEPack
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormICEPack());
}
public static OpenDB(string DBServer, string DBDatabase, string DBLogin_ID, string DBPassword)
{
MessageBox.Show(DBServer + ", " + DBDatabase + ", " + DBLogin_ID + ", " + DBPassword + "...In Program.cs");
SqlConnection IPConnection = new SqlConnection();
IPConnection.ConnectionString =
@"Server=" + DBServer + ";"
+ "Database=" + DBDatabase + ";"
+ "User ID=" + DBLogin_ID + ";"
+ "Password=" + DBPassword + ";";
IPConnection.Open();
}
}
}
GustavoPosted Mar 10, 2010, 3:57 PM
I did put the database connection in the parent. I will re-read your post and try to figure it out. I never used that program.cs item. I will look into it. Thanks.
Sam HobbsPosted Mar 10, 2010, 3:53 PM
GustavoPosted Mar 10, 2010, 1:07 PM
Ok, I have finnaly figured out how to create a class. However, how do I pass the database connection back to the MDIParent? Below is mu code for the class.
namespace ICEPack
{
public partial class ClassDB
{
public void OpenDB(string DBServer, string DBDatabase, string DBLogin_ID, string DBPassword)
{
MessageBox.Show(DBServer + ", " + DBDatabase + ", " + DBLogin_ID + ", " + DBPassword + "...");
SqlConnection IPConnection = new SqlConnection();
IPConnection.ConnectionString =
@"Server=" + DBServer + ";"
+ "Database=" + DBDatabase + ";"
+ "User ID=" + DBLogin_ID + ";"
+ "Password=" + DBPassword + ";";
IPConnection.Open();
//return IPConnection;
}
public void Test()
{
MessageBox.Show("I am here, in ClassDB.Test...");
}
}
}
GustavoPosted Mar 10, 2010, 10:01 AM
When you say: "proper database management class.". Do you mean a school/college/uiniversity class or a class like in a program like class1.cs ?
Lead me to where I should find this.
Hirendra SisodiyaPosted Mar 10, 2010, 3:24 AM
some ideas:
1. you can add new public static class and put your sql connection code in this class, so that you can use any where in project.
2. you can make property for sql connection.
3. you can pass sqlconnection through making constructor.
theLizardPosted Mar 10, 2010, 2:12 AM
No disrespect,
What you are attempting to do is NOT, I repeat, is NOT a good practice.
I have suggested Forms Management and database management frameworks, you have chosen not to take my advice now we are asking for help regarding something that would have been addressed in a proper database management class.