I have this error studentHelperClass.Form1.cmbBox is inaccessible due to its protection level
for this part of my code
class studentHC : Form1
{
public studentHC()
{
InsertMethod();
}
private void InsertMethod()
{
MySqlConnection conn; // connection object;
string connstring =
"server=localhost;user Id=root;" +
"database=collegesystem;Convert Zero Datetime=True ";
conn = new MySqlConnection(connstring);
conn.Open();
using (var command = new MySqlCommand("SELECT * FROM person", conn))
{
using (var myReader = command.ExecuteReader())
{
cmbBox.Items.Add(myReader["personID"]);
}
}
}
internal static void insertMethod()
{
throw new NotImplementedException();
}
the above code is for a SELECT query to display the contents of a table called person
and this I have in my Form
public partial class Form1 : Form
{
MySqlConnection conn; // connection object;
string connstring =
"server=localhost;user Id=root;" +
"database=collegesystem;Convert Zero Datetime=True ";
public Form1()
{
InitializeComponent();
connection();
selectStudent();
}
private void selectStudent()
{
try
{
studentHelperClass.studentHC.insertMethod();
}
catch (Exception err)
{
lblInfo.Text = " Error reading the database.";
lblInfo.Text += err.Message;
}
}
How can I solve this error?
I believe that this is the last error before the program will work
EDIT:
this is thee only part of the code I didn't show you..and it has nothing to do with cmbBox :/
private void connection()
{
try
{
conn = new MySqlConnection(connstring); //make the connection object
conn.Open(); // try and open the connection
lblInfo.Text = " server version: " + conn.ServerVersion;
lblInfo.Text += "\n Connection is :" + conn.State.ToString();
}
catch (Exception err)
{
lblInfo.Text = " Error reading the database.";
lblInfo.Text += err.Message; ;
}
EDIT NUMBER 2:
private void InitializeComponent()
{
this.cmbBox = new System.Windows.Forms.ComboBox();
this.lblInfo = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// cmbBox
//
this.cmbBox.FormattingEnabled = true;
this.cmbBox.Location = new System.Drawing.Point(65, 9);
this.cmbBox.Name = "cmbBox";
this.cmbBox.Size = new System.Drawing.Size(121, 21);
this.cmbBox.TabIndex = 0;
I have to change that to public?
Ok so I used the properties window to change cmbBox to protected and that removed the error, but now my label for statuses on the database has given me this error after I ran the program, any idea why?
Error reading the database, method or operation is not implemented
I think you need to open auto generated partial class of Form1 and change cmbBox to protected. This can be done from the designer view also if you are using Visual Studio. This should solve the problem.
I suspect that cmbBox was declared as private (or maybe you didnt declare any protection level, and it defaults to private). If you can, please change it to be protected instead.
If you can't change it for some reason, try:
public partial class Form1 : Form
{
protected void AddPerson(Person p)
{
cmbBox.Items.Add(p);
}
}
and
class studentHC : Form1
{
public studentHC()
{
InsertMethod();
}
private void InsertMethod()
{
MySqlConnection conn; // connection object;
string connstring = "server=localhost;user Id=root;database=collegesystem;Convert Zero Datetime=True ";
conn = new MySqlConnection(connstring);
conn.Open();
using (var command = new MySqlCommand("SELECT * FROM person", conn))
{
using (var myReader = command.ExecuteReader())
{
AddPerson(myReader["personID"]);
}
}
}
}
If the ComboBox is created by IDE,most probably the ComboBox will have been declared Private.Try setting it to Protected under category Modifiers in the Properties Window.
Right click on the "cmbBox" object in the Form view. You need to set it's "Modifier" level to Public or Protected.
Related
I have a form that checks whether values are in a database before adding them. Each field is in a different table, and to keep everything clean, I have a checkExists method for each field. Is there a way to have a separate method that connects to the database, so that I don't have to connect in every field method?
I'd like to do something like this so that my code is less messy:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
But I get a
local variable set_conn
Argument 2: Cannot Convert from Class_DB to System.Data.SqlClient.SqlConnection
I understand the error, so what can I do to return the correct value, or do I have to establish a connection within my CheckData_Comany() method?
Your method SetConnection should be returning SqlConnection back like:
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
and then you can have something like:
SqlConnection connection = set_conn.SetConnection();
and then pass it in SqlCommand constructor as parameter :
SqlCommand check_Company = new SqlCommand(query_string, connection);
Your complete method implementation would become :
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
and important thing to note is do not forget the close the connection finally by calling connection.Close(), otherwise it might cause eating up the resources that shouldn't happen when we are done with querying the database and we should release the resources occupied.
I want to connect to a SQL Server database when I'm at home and outside. I can connect in both ways but I need to change connection string every time from public ip to local when I'm home. Is it possible to write a function that whenever it cannot connect via remote ip to use other hostname in connection string?
Please help I'm a beginner :)
Try this:
//.....
//.....
//..... YOUR CODE
try
{
con = new SqlConnection(check_Active_Connection_String()); // Add this
con.Open();
SqlCommand r = new SqlCommand("SELECT Login FROM Users WHERE Login not like '%Wszyscy%'", con);
//.... YOUR CODE
//.... YOUR CODE
Hope it helps.
This is my code after adding yours Dheeraj. Error is at con.Open(); line
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection con;
private string CS_1 = #"Data Source=99.88.88.156,33400\SQLMINFOR;Initial Catalog=Minfor;Integrated Security=False;Password=****;User ID=sa;";
private string CS_2 = #"Data Source=BACKUP-MIN\SQLMIN;Initial Catalog=Minfor;Integrated Security=False;Password=****;User ID=sa;";
public string check_Active_Connection_String()
{
string main_CS = "";
if (try_CS(CS_1))
{
main_CS = CS_1;
}
else if (try_CS(CS_2))
{
main_CS = CS_2;
}
return main_CS;// use main_CS for your connection string further
}
private bool try_CS(string CS)
{
try
{
using (con = new SqlConnection(CS))
{
con.Open();
return true;
}
}
catch (Exception exp)
{
return false;
}
}
public Form1()
{
InitializeComponent();
textBox2.PasswordChar = '*';
try
{
con.Open();
SqlCommand r = new SqlCommand("SELECT Login FROM Users WHERE Login not like '%Wszyscy%'", con);
SqlDataReader dr = r.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["Login"]);
}
dr.Close();
dr.Dispose();
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
I am missing something very simple. I have a form with 5 textBox and want to fill them with the data from the SQL Server database. Here is what I have so far:
As I debug this code line by line it returns to the calling block at the connection.open() line.
public void Get_Contact_Info()
{
using (DataAccessClass.sql_Connection)
{
string SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
SqlCommand sqlCommand = new SqlCommand(SQL, DataAccessClass.sql_Connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
sqlCommand.Parameters.AddWithValue("#Contact_Direct_Number", contact_Direct_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Cell_Number", contact_Cell_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Email", contact_EmailTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Department", contact_DepartmentTextBox);
DataAccessClass.sql_Connection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
}
DataAccessClass.sql_Connection.Close();
}
}
}
I have been doing a pretty good job of getting info from the user and saving it to the SQL Server DataTable but know I want to get some out so that I can edit the info.
Any help will be gratefully appreciated.
Here is my DataAccessClass
public static class DataAccessClass
{
static SqlConnection sqlConnection = new SqlConnection();
public static SqlConnection sql_Connection
{
get { return sqlConnection; }
}
public static void OpenConnection()
{
string sqlString = Properties.Settings.Default.ConnectionString;
sqlConnection.ConnectionString = sqlString;
sqlConnection.Open();
}
public static void CloseConnection()
{
sqlConnection.Close();
}
}
Here is how I am calling Get_Contact_Info.
private void Customer_Add_Contact_Form_Load(object sender, EventArgs e)
{
this.customer_ContactsBindingSource.AddNew();
if (contact_Id == null)
{
contact_NameTextBox.Select();
}
else
{
Get_Contact_Info();
}
}
From a DataGridView I am selecting a row and passing customer_ID to the Customer_Add_Contact_Form so that I can edit the contact information. Here is the code for this step:
DataGridViewRow row = customer_ContactsDataGridView.CurrentCell.OwningRow;
string contact_ID = row.Cells[0].Value.ToString();
string customer_Ship_ID = null;
using (Form Customer_Add_Contact_Form = new Customer_Add_Contact_Form(customer_Ship_ID, contact_ID))
As discussed here it is better to let connection pooling manage the connections, so you can simplify your code to:
public void Get_Contact_Info()
{
using (var connection = new SqlConnection(roperties.Settings.Default.ConnectionString))
{
connection.Open();
var SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
var sqlCommand = new SqlCommand(SQL, connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
TextBoxName.Text = sqlDataReader["Contact_Name"].ToString();
//etc ...
}
}
}
}
I have removed unused parameters and created a new connection. Possibly you tried to open a connection using .Open() without initializing it with a connections string (is it roperties?)
I've got several forms, some of which rely on information between each form. In this case, the selected index of the chosen option in Form 2 (AKA testSelect) is key to determining what will happen in Form 3 (AKA testPresent). This is placed into an integer called index. Upon closing form 2 the value of index is definitely whatever the selectedindex of the listbox is.
However upon opening and applying it in form 3 it resets to 0 all the time, and I can't figure out why. below is the code where index is used/determined in form 2 as well as the code where it is called in form 3. Also, it is a public int defined at the start of form 2;
private void lstExams_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//Create a connection object to the DB via string location
con = new OleDbConnection(connectionString);
//Open the connection to the DB
con.Open();
String sql = "SELECT typeID, description FROM TestConfiguration WHERE examID = " +(lstExams.SelectedIndex +1);
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
//DataSet ds = new DataSet();
DataTable testConfig = new DataTable();
//Set the SQL command text
da.Fill(testConfig);
lstTestType.DisplayMember = "description";
lstTestType.ValueMember = "typeID";
lstTestType.DataSource = testConfig;
index = lstExams.SelectedIndex + 1;
MessageBox.Show("INDEX = " + index);
}
catch (Exception err)
{
//If cannot connect to DB, display the error;
MessageBox.Show("A Database error has occurred: " + Environment.NewLine + err.Message);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
//var testPresent = new testPresent(this);
testPresent testForm = new testPresent();
testForm.Show();
//testForm.difficulty = lstTestType.ValueMember;
this.Close();
MessageBox.Show("INDEX IS " + index);
testForm.eID = (index);
}
And for form 3
public partial class testPresent : Form
{
public int eID = 0;
public String difficulty;
testSelect select = new testSelect();
//Get the connection path to the DB from the static class
String connectionString = staticConnectionString.connectionString;
//Declare connection object
OleDbConnection con;
public testPresent()
{
InitializeComponent();
}
public void testPresent_Load(object sender, EventArgs e)
{
try
{
int qID;
Random random = new Random();
int examID;
bool valid = false;
String theQuestion;
eID += select.index;
//Create a connection object to the DB via string location
con = new OleDbConnection(connectionString);
//Open the connection to the DB
con.Open();
MessageBox.Show("eID = " + select.index);
if (eID == 1)
{
...
}
if (eID == 2)
{
...
}
if (eID == 3)
{
...
}
}
catch (Exception err)
{
//If cannot connect to DB, display the error;
MessageBox.Show("A Database error has occurred: " + Environment.NewLine + err.Message);
}
}
Oh yeah, this also uses Microsoft Access Databases to populate the listbox.
You set the value:
testForm.eID = (index);
But you do so after the form has already been loaded, so testPresent_Load has already used its default value:
testPresent testForm = new testPresent();
testForm.Show(); // this is where it uses the value
// ...
testForm.eID = (index); // this is where you set it
If the value is required for the testPresent form entirely, and it needs the value right away, try including the value in the constructor:
public testPresent(int eid)
{
InitializeComponent();
eID = eid;
}
Then when you create an instance of the form you'd have to pass it that value:
testPresent testForm = new testPresent(index);
testForm.Show();
At that point there'd be no need to set the value externally, so it should be private. (Data members should be private on objects anyway.):
private int eID;
What am I doing wrong here? I am trying to display data from a remote database and inserting,editing, and deleting data. The database that I am connecting to is a remote which I was successfully able to connect and view the information however when I insert the syntax to edit the data I get an error (see bottom of the post).
I am using Devexpress Scheduler Controller to view appointments as well edit them.
This is the entire code.
public partial class MainWindow : Window
{
CarsDBDataSet dataSet;
public MainWindow()
{
InitializeComponent();
intSchedular();
}
private void intSchedular()
{
schudlerControl1.Storage.AppointmentStorage.Mappings.AllDay = "AllDay";
schudlerControl1.Storage.AppointmentStorage.Mappings.Description = "Description";
schudlerControl1.Storage.AppointmentStorage.Mappings.End = "EndTime";
schudlerControl1.Storage.AppointmentStorage.Mappings.Label = "Label";
schudlerControl1.Storage.AppointmentStorage.Mappings.Start = "StartTime";
schudlerControl1.Storage.AppointmentStorage.Mappings.Location = "Location";
schudlerControl1.Storage.AppointmentStorage.Mappings.ReminderInfo = "RemindderInfo";
schudlerControl1.Storage.AppointmentStorage.Mappings.Subject = "Subject";
schudlerControl1.Storage.AppointmentStorage.Mappings.Status = "Status";
schudlerControl1.Storage.AppointmentStorage.Mappings.Type = "EventType";
schudlerControl1.Storage.AppointmentStorage.Mappings.RecurrenceInfo = "RecurrenceInfo";
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection()
{
ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + #"Data source= \\UNDERFOOT-PC\CalUnderFootDB\CarsDB.mdb"
};
con.Open();
OleDbCommand createCommand = new OleDbCommand("select * from CarScheduling", con);
createCommand.ExecuteNonQuery();
OleDbDataAdapter adapter = new OleDbDataAdapter(createCommand);
CarsDBDataSet dataSet = new CarsDBDataSet();
// Bind the scheduler storage to appointment data.
schudlerControl1.Storage.AppointmentStorage.DataSource = dataSet.CarScheduling;
// Load data into the 'CarsDBDataSet.CarScheduling' table.
adapter.Fill(dataSet.CarScheduling);
schudlerControl1.Storage.AppointmentsInserted +=
new PersistentObjectsEventHandler(Storage_AppointmentsModified);
schudlerControl1.Storage.AppointmentsChanged +=
new PersistentObjectsEventHandler(Storage_AppointmentsModified);
schudlerControl1.Storage.AppointmentsDeleted +=
new PersistentObjectsEventHandler(Storage_AppointmentsModified);
adapter.Adapter.RowUpdated +=
new System.Data.OleDb.OleDbRowUpdatedEventHandler(adapter_RowUpdated);
}
void Storage_AppointmentsModified(object sender, PersistentObjectsEventArgs e)
{
adapter.Adapter.Update(dataSet);
this.dataSet.AcceptChanges();
}
private void adapter_RowUpdated(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
{
if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
{
int id = 0;
using (OleDbCommand cmd = new OleDbCommand("SELECT ##IDENTITY", adapter.Connection))
{
id = (int)cmd.ExecuteScalar();
}
e.Row["ID"] = id;
}
}
}
The error I am getting is from the word adapter from "void Storage_AppointmentsModified" saying "the name 'adapter' does not exist in the current context". I know I have to define adapter but how? I am new to C# so I am not "fluent" with writing C# syntax.
You have defined the adapter variable inside the intSchedular method. But this variable is local to that method and cannot be used outside of it (It will be destroyed when you exit from intSchedular)
To be able to use the variable in Storage_AppointmentsModified, you need to define it at the global class scope like you already do with the CarsDBDataSet
public partial class MainWindow : Window
{
CarsDBDataSet dataSet;
OleDbDataAdapter adapter;
.....
private void intSchedular()
{
.....
adapter = new OleDbDataAdapter(createCommand);
.....
}
void Storage_AppointmentsModified(object sender, PersistentObjectsEventArgs e)
{
this.adapter.Update(dataSet);
this.dataSet.AcceptChanges();
}
Another thing to fix in your code is the Handling of the connection. A Connection should be used following a precise pattern. Create, Open, Use, Close and Destroy. You should be using the using statement in your intSchedular to be sure of the destruction of the connection
private void intSchedular()
{
// CREATE
using(OleDbConnection con = new OleDbConnection(... con string here....))
using(OleDbCommand createCommand = new OleDbCommand("select * from CarScheduling", con))
{
// OPEN
con.Open();
// NO USING HERE BECAUSE WE WANT THE ADAPTER OUTSIDE OF THIS METHOD
adapter = new OleDbDataAdapter(createCommand);
// USE
....
adapter.Fill(dataSet.CarScheduling);
....
} // CLOSE + DISPOSE
}
The same thing should be done in the adapter_RowUpdated
private void adapter_RowUpdated(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
{
if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
{
int id = 0;
using (OleDbConnection con = new OleDbConnection( .... con string here ....))
using (OleDbCommand cmd = new OleDbCommand("SELECT ##IDENTITY", con))
{
con.Open();
id = (int)cmd.ExecuteScalar();
}
e.Row["ID"] = id;
}
}