Issues with configuration manager [duplicate] - c#

This question already has answers here:
ConfigurationManager return null instead of string values
(4 answers)
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I am creating a website that acts as a form, but includes two cascading drop down lists (so one feeds from the other). I have used the following example to create my lists (I am fairly new to c# .net development so needed to work through a tutorial)
https://www.aspsnippets.com/Articles/Populate-Cascading-DropDownList-from-Database-in-ASPNet-Example.aspx
I have changed all the relevant areas of code to point to the right tables and database for my query. When I run the application I am getting an issue with Configuration Manager. I looked this up and followed the instructions in this feed:
The name 'ConfigurationManager' does not exist in the current context
I hit f5 to run in visual studio and got a slightly different error of a non legal operation, so applied the advice here:
Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state
After all of this I am still getting the following:
Exception User-Unhandled
System.NullReferenceException: 'Object reference not set to an instance of an object'
System.Configuration.ConnectionStringSettingCollection.this[string].get returned null.
Here is my code:
<connectionStrings>
<clear/>
<add name="conString"
connectionString="Data Source=CATE01-SRV-05;
Initial catalogue=iSAMS;Integrated Security=true"/>
</connectionStrings>
public partial class CoCurricular : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CategorySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select TblActivityManagerFolderID, txtName from dbo.TblActivityManagerFolder";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
CategorySelect.DataSource = cmd.ExecuteReader();
CategorySelect.DataTextField = "txtName";
CategorySelect.DataValueField = "TblActivityManagerFolderID";
CategorySelect.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ActivitySelect.Items.Clear();
ActivitySelect.Items.Add(new ListItem("--Select Activity--", ""));
ActivitySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select txtName from dbo.TblActivityManagerGroup " +
"where intFolder=#TblActivityManagerFolderID";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#TblActivityManagerFolderID",
CategorySelect.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ActivitySelect.DataSource = cmd.ExecuteReader();
ActivitySelect.DataTextField = "txtName";
ActivitySelect.DataValueField = "TblActivityManagerGroupID";
ActivitySelect.DataBind();
if (ActivitySelect.Items.Count > 1)
{
ActivitySelect.Enabled = true;
}
else
{
ActivitySelect.Enabled = false;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
}

Related

Retrieving information stored in a SQL Server CE database in Visual Studio 2010

I asked a question [HERE] and we got all the information stored in the database SQL Server CE database.
The question remains now how to get the information stored back into variables.
This line of code:
myReader.SqlCeReader();
will not compile, I am asked if I have missed a compiler reference what ever that is.
The information is stored as strings with an Integer “ID” primary key.
The information will be used to create shortcuts on a disk suitable for launching, images in paint, executable programs and so on. They should not be more than strings which is why I find it hard to do, it should be simple.
A sample record
id=int NstacksName=String NstacksPath=String.
I think I have it all wrong and am surprised it even compiles this far.
private void label2_Click(object sender, EventArgs e)
{
string DirName;
SqlCeConnection conn = new SqlCeConnection("Data Source=C:\\Users\\username\\Documents\\Visual Studio 2010\\Projects\\NStacks1\\NStacks1\\Database1.sdf");
String name;
try
{
conn.Open();
SqlCeCommand Command = new SqlCeCommand("SELECT * FROM NStacks1 WHERE ID = 1", conn);
DataTable Data = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(Command);
SqlCeDataReader myReader;
try
{
myReader.SqlCeReader();
DirName = Data.ToString();
con.Close();
name = DirName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
private void button4_Click(object sender, EventArgs e)
{
string SName, NStackPath;
string source=("Data Source=C:\\Users\\username\\Documents\\Visual Studio 2010\\Projects\\NStacks1\\NStacks1\\Database1.sdf");
SqlCeConnection Con = new SqlCeConnection(source);
try{
Con.Open();
string Query= "SELECT * FROM Nstacks1 WHERE ID=1";
SqlCeCommand command = new SqlCeCommand(Query , Con);
SqlCeDataReader dr = command.ExecuteReader();
if (dr.Read())
{
textBox1.Text=(dr["NStacksName"].ToString());
label2.Text = (dr["NStacksItem"].ToString());
}
Con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
}

C# error: Object reference not set to an instance of an object, but do not know how getting NULL [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I'm testing the code that I got as an example to try, but I'm getting the error
Object reference not set to an instance of an object
I did look into the meaning of this error which I found out it occurs when the object references NULL.
The error is generated on this line
string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
The only problem is I do not know how the NULL is being generated, hence, unable to fix.
How can I resolve this?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select CountryId, CountryName from Countries";
BindDropDownList(ddlCountries, query, "CountryName", "CountryId", "Select Country");
ddlStates.Enabled = false;
ddlCities.Enabled = false;
ddlStates.Items.Insert(0, new ListItem("Select State", "0"));
ddlCities.Items.Insert(0, new ListItem("Select City", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
con.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
There is a file in your project called a web.config. The "conString" references the exact connection in the web.config look at the example in the following documentation for more information. They use northwind instead of conString. If ConString does not exist you will get a null reference which is C# saying I can't find that connection string and I can't continue
https://msdn.microsoft.com/en-us/library/ms178411.aspx

Database connection C#

I have a question according to this code. VisualStudio shows no errors or warnings but when I run it, the result is only the exceptionerror ("Something went wrong."). This is how I have always done it before but somehow always worked except for now. Am I missing a simple thing?
protected void Page_Load(object sender, EventArgs e)
{
// Connect
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\royva\documents\visual studio 2013\Projects\CookieMultiView\CookieMultiView\App_Data\Databank.mdb';Persist Security Info=True";
// Execute
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM teachers = ?";// + Request.QueryString["id"];
lbl.Text = "";
cmd.Parameters.AddWithValue("id",Request.QueryString["id"]);
// Read
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
lbl.Text = reader["teacherid"].ToString();
}
}
catch (Exception ex)
{
//lbl.Text = ex.StackTrace;
lbl.Text = "Something went wrong.";
}
finally
{
conn.Close();
}
For Detailed info of the Exception,
catch (Exception ex)
{
//Either you can write log or display in label
lbl.Text = ex.Message;
}
Also check the folder access rights for
Data Source='C:\Users\royva\documents\visual studio 2013\Projects\CookieMultiView\CookieMultiView\App_Data\Databank.mdb'
Programmatically to check for specific files use File.Exists(path), which will return a boolean indicating whether the file at path exists.
And validate if the connection has been established or not.

Display DateTime iin C# and WPF

I have a DateTime variable selected in a 1st window and I'm trying to display in in a 2nd window. It connects to the DB as it should be,but it appears a random data from the DB,not the selected one.
Here is the code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Are you sure?");
Window1 win1 = new Window1();
win1.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
{
string connectionString = null;
SqlConnection cnn;
connectionString =
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True";
try
{
SqlConnection con =
new SqlConnection(
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"insert into [Event] (Description,StartData,EndData,Type) values (#description,#startdata,#endata,#type)";
cmd.Parameters.AddWithValue("description", descriptionTxt.Text);
cmd.Parameters.AddWithValue("startData", StartDate.Value);
cmd.Parameters.AddWithValue("endata", EndDate.Value);
cmd.Parameters.AddWithValue("type", typeTxt.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
////Window2 win = new Window2(id);
//Window2 win3 = new Window2();
//this.Close();
//win3.Show();
SqlConnection conn =
new SqlConnection(
#"Data Source=IBWS05\MSSQLSERVER2012;Initial Catalog=Interview;Integrated Security=True");
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
int query= Convert.ToInt32(comm.CommandText = "select MAX(StartData) from [Events]");
Window2 win = new Window2(query);
win.Show();
}
The error is input string was not in a correct format. How can I convert it?
There are a few things you need to look at/consider in your code, first is your issue.
This line of code:
int query= Convert.ToDateTime(comm.CommandText = "select MAX(DateTime) from [Events]");
Won't achieve what you are after as you aren't executing the code. You are actually trying to convert your command object to a Date Time.
Earlier in your method you are writing to the database and part of that you call the following:
cmd.ExecuteNonQuery();
There are various other methods that you have on the command object that all work in different ways. To read about them visit this MSDN page, but essentially you probably want to use the ExectuteScalar method for what you are trying to do.
Next, I would consider moving your connection string to the app.config file and accessing it from there rather than typing it out multiple times.
And finally, I would use a using statement for each of your Connection's so that you ensure they are being disposed of correctly.
Just some extra food for thought.

update a mySQL table using C#

I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

Categories

Resources