System.InvalidOperationException: 'The ConnectionString property has not been initialized.' - c#

I am trying to fill list boxes with elements and been doing everything by a clean guide but I am getting connection string error when I am trying to run it.
Clearly i have done something foolish and can't understand it so a deeper explanation would be appreciated
The error
The ConnectionString property has not been initialized.
The Code
public partial class FormMain : Form
{
SqlConnection connection;
string connectionString;
public FormMain()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["NaujasAutoSalonas.Properties.Settings.AutoSalonasConnectionString"].ConnectionString;
}
private void FormMain_Load(object sender, EventArgs e)
{
PopulateAutoKlases();
}
private void PopulateAutoKlases()
{
using (connection = new SqlConnection(connectionString));
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM AutoKlases", connection))
{
DataTable KlasesTable = new DataTable();
adapter.Fill(KlasesTable);
lstKlases.DisplayMember = "KlasesPavadinimas";
lstKlases.ValueMember = "KlasesID";
lstKlases.DataSource = KlasesTable;
}
}
}

As you have stated that the connection string property is not initialized,so I guess that your applications is not able to read the connection string from the config file.You can confirm this by putting a breakpoint in the constructor of FormMain class.
If the connection string is not being set in the constructor then you need to identify whether you have declared the connection string properly in your config file.As there could be few config files ,so it is important that you declare your connection string in the correct config file.
Or if you are defining properties for your connection string in the .settings file,you can validate if you are accessing it correctly.

Related

Can't use MySqlConnection methods outside function

I am new coding and I am trying to create a model DBContext.
I instantiated a connection conn using MySqlConnection. Then I perceived it didn't me allow to use conn methods (like conn.Open()).
I have found a code that uses it inside a function and it seems to work. However I couldn't understand why it has to be inside a function.
Here is my code:
public class DBContext
{
//Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
//start creating connection string
public static string ConnectString
{
get { return "Server=localhost;Database=blog;Uid=root;Pwd=root;"; }
}
public string ConnectionTest()
{
//create an instance of connection
MySqlConnection conn = new MySqlConnection();//Here I can use conn properties/methods
return "";
}
//create an instance of connection
MySqlConnection conn2 = new MySqlConnection();//Here I can't
conn2.open();
}
After reading some documentation about classes and method I understand that classes are references therefore it will not "run".
However I couldn't understand why the error when using conn2.open() is
conn2.open() does not exist in the current context.
shouldn't conn2 exist in the "class context"?

Issue Getting "The ConnectionString property has not been initialized."

I an working on window application and i have one method for checking the connection is open if open then closed and i have a single instance of connection object but i am getting the issue "The ConnectionString property has not been initialized."
Here is my code:
public static SqlConnection connection { get; set; }
public static SqlConnection GetOpenConnnection()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
if (connection == null)
connection = new SqlConnection(ConnectionString);
if (connection.State == ConnectionState.Open)
connection.Close();
return connection;
}
Please tell me why i am getting this issue, if i create connection object every time then its working. so please tell me cant i have one connection object for whole application.

can't find the logical error in c# asp.net below

I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.

The name 'sqlDbType' does not exist in the current context

I'm going to edit textbox value.. but i saw there's a problem
protected void btn_edit_Click(object sender, EventArgs e)
{
DatabaseConnector con = new DatabaseConnector().CreateInstance();
SqlCommand com = new SqlCommand("UPDATE tbl_BinCardManager SET ItemName = #ItemName WHERE ItemNo = #ItemNo");
com.Parameters.Add("#ItemName",sqlDbType.VarChar);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
ERROR 1:
The name 'sqlDbType' does not exist in the current context
ERROR 2:
'ERPSystem.DatabaseConnector' does not contain a definition for 'Open'
and no extension method 'Open' accepting a first argument of type
'ERPSystem.DatabaseConnector' could be found (are you missing a using
directive or an assembly reference?)
My DBConnector Class is :
class DatabaseConnector
{
private DatabaseConnector databaseConnector;
private string connectionString = "Data Source=lernlap;Initial Catalog=ERPSystemDB;User ID=sa;Password=sa123";
public DatabaseConnector()
{
}
private SqlConnection connection;
private bool Connect()
{
try
{
connection = new SqlConnection(connectionString);
connection.Open();
return true;
}
catch(Exception) {
return false;
}
}
internal DatabaseConnector CreateInstance()
{
if (databaseConnector == null)
{
databaseConnector = new DatabaseConnector();
databaseConnector.Connect();
}
return databaseConnector;
}
C# is case sensetive... Try using intellisense.
SqlDbType
The other errors may disappear if you correct the first one.
On a side note, you're going to run into connection/memory leaks without proper resource handling. Personally, I use the using statement to avoid the pitfalls.
I'm not entirely certain what "DatabaseConnector" is, possible your own class, but you should probably be using SqlConnection instead, or possibly SqlDatabase.
Update: I'm not sure if the DBConnector class is supposed to be a singleton or a factory, or both - so I just simplified my answer to avoid using it. Ask another question with detail on how to create the pattern you're looking for and provide the DBConnector class. I think it's do-able, but I just don't have enough info to fix what you have.
public static CONN_STR = "Data Source=lernlap;Initial Catalog=ERPSystemDB;User ID=sa;Password=sa123";
protected void btn_edit_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(CONN_STR))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("UPDATE tbl_BinCardManager SET ItemName = #ItemName WHERE ItemNo = #ItemNo"), con)
{
// TODO: fill in param values with real values
cmd.Parameters.AddWithValue("#ItemName", "my item name");
cmd.Parameters.AddWithValue("#ItemNo", 1);
cmd.ExecuteNonQuery();
}
}
}
SqlDbType the s needs to be capitalized!
yes but theres no any case sensitivity problem know
You actually DO have syntax errors because you used s instead of S. Furthermore
SqlCommand does not have a method called Open() nor does it have one for Close()
You should be using SqlConnection since it contains the methods Open() and Close() and set the SqlCommand's Connection property to your instance of SqlConnection in order to open and close the connection to your database.
You have more errors.
Based on the way you use it, I think you mean SqlConnection instead of DatabaseConnector
You create an SqlCommand named com, but refer to it as cmd
You will need to assign the SqlConnection to the SqlCommand, or it will not know which connection to open.
You only provide 1 parameter to the SqlCommand, while the query needs two (ItemNo as well as ItemName).
Edit, based on your new source:
The error "DatabaseConnector' does not contain a definition for 'Open'" can be corrected by writing con.Connect() instead of con.Open().
However, the other error, that it doesn't have a "Close()" function, can't be corrected - there is no way to tell it to close a connection.
Is this your own code?
Are you using the class made by The Code Project ?
Well, I think the error is because the connection string. The connection string have to be in the class OdbcDatabaseConnector. Well, I never used this class of Code Project, but can be it.
If you are writing with capital 'S' but still get the same error especially in visual studio 2015, then instead of writing 'SqlDbType' , write :
System.Data.SqlDbType
for example:
param[0] = new SqlParameter("#Name", System.Data.SqlDbType.VarChar,50);
Its capital 'S' in SqlDbType, after making the correction, right click on the word, mouse on over to resolve option and add the System.Data namespace. worked for me!

How to create an EntityConnection

I have a Solution with multiple projects.
One project is my DataAccess project with 2 SQL CE databases defined, one for local users and one for company data, both with similar table structures. Public, static, readonly strings are defined for each database, and connections can be made.
Another project is my WPF project that will (eventually) display my data. To display data here, I have tried creating an Entity Context object, but nothing seems to work.
What is preventing me from accessing my data in the other project? (Currently, error states 'data source' is not defined)
How do I fix it?
AbcEntities abcContext;
public MainWindow() {
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
EntityConnection ec = new EntityConnection(DataClass.AbcConnectionString);
abcContext= new AbcEntities(ec);
listbox1.ItemsSource = from c in abcContext.Customers select c;
abcCustomersBox.DisplayMemberPath = "Name";
} catch (Exception err) {
MessageBox.Show(err.Message);
}
}
For others, I found out how to do this.
In my static DataClass, I created the following routine to generate the Entity Connection String for me:
static string BuildEntityConnString(string dbFileName, string resourceData, string password) {
string resAll = #"res://*/";
string dataSource = #"Data Source=|DataDirectory|\" + dbFileName;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Metadata = string.Format("{0}{1}.csdl|{0}{1}.ssdl|{0}{1}.msl", resAll, resourceData);
entityBuilder.Provider = "System.Data.SqlServerCe.3.5";
if (String.IsNullOrEmpty(password)) {
entityBuilder.ProviderConnectionString = dataSource;
} else {
entityBuilder.ProviderConnectionString = dataSource + ";Password=" + password;
}
using (EntityConnection con = new EntityConnection()) {
try {
con.ConnectionString = entityBuilder.ToString();
con.Open();
Console.WriteLine("{0} Entity String created.", dbFileName);
con.Close();
return con.ConnectionString;
} catch (Exception err) {
Console.WriteLine(err);
}
}
return null;
}
Notice that if there is any error, a NULL String is returned.
If anyone wants to use this, they should either place a breakpoint at the Exception, throw it, or handle it in some way. The Console.WriteLine() was just for me to debug through this.
I created Entity Connection Strings for my applications as follows:
public static readonly string EntityConnString =
BuildEntityConnString("sqlCeDb.sdf", "myModel", "abc123~Funky");
Hope others get some mileage out of this.
Explanation (more of an example, really) of how to create an EntityConnection can be found on MSDN here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx
Looks pretty similar to what you have.

Categories