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.
Related
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();
}
}
}
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();
}
}
}
private void Update_Click(object sender, EventArgs e)
{
string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");
OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location=? WHERE itemID='1' ", con);
com.Parameters.Add("#loca", OleDbType.VarChar).Value = loca;
con.Open();
try
{
com.ExecuteNonQuery();
}
catch(Exception f)
{
MessageBox.Show(f.Message);
//MessageBox.Show("Given Data is not Valid", "Cannot Add", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();
gridview();
}
Here I have changed the code no error m getting is
No value given for one or more required parameters
Update query is not working so please help me with it.
In C# you need to add an actual parameter object and give it a value:
string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");
OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location= ? WHERE itemID='1'", con);
com.Parameters.Add("#loca", OleDbType.VarWChar).Value = loca ?? (object)DBNull.Value;
Some other suggestions/habits to get in to:
Wrap your connections and commands in using blocks so that they get disposed of in a timely manner
Do not just catch an exception and show a vague message. Either include the exception details or log it somewhere so that you know what the actual error is.
This is code i wrote to add some text to accordion pane on a button click:
protected void Button1_Click1(object sender, EventArgs e)
{
//Use a string variable to hold the ConnectionString.
string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb";
System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection();
cn.ConnectionString = connectString;
//Create an OleDbConnection object, and then pass in the ConnectionString to the constructor.
//OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString);
try
{
//Open the connection.
cn.Open();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl("Open Error"));
}
string selectString = "SELECT * FROM BasicInfo";
//Create an OleDbCommand object.
//Notice that this line passes in the SQL statement and the OleDbConnection object
OleDbCommand cmd = new OleDbCommand(selectString, cn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
//Note: The OleDbDataReader is forward-only.
try
{
OleDbDataReader reader=null;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception es)
{
AccordionPane1.Controls.Add(new LiteralControl(" datareader"));
}
string s = "s";
reader.Read();
s = reader["S_No"].ToString();
AccordionPane1.Controls.Add(new LiteralControl(s));
//Close the reader and the related connection.
reader.Close();
cn.Close();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl(" Read Error"));
}
}
I have my access 2007 database in the folder i specified in the connectString. When im viewing in the browser, on the button click i am getting all the three exceptions:
What might be the problem in opening the database? Do i need to make any other changes?
Change
Provider=Microsoft.Jet.OLEDB.4.0;
to
Provider=Microsoft.ACE.OLEDB.12.0
Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb
Hopefully it will solve the issue.
you connection string might be cause of isssue
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\abc.mdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
this For access 2007 also check the path of database is cocrect.
You can use |DataDirectory| instead of real path and you have to change the Provider=Microsoft.ACE.OLEDB.12.0 (as suggested by #MMK)
string connectString = #"Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\Students1.accdb;Persist Security Info=False;";
and always use using block which dispose IDisposable objects properly.
using(OleDbConnection cn=new OleDbConnection())
{
using(OleDbCommand cmd=new OleDbCommand())
{
cn.ConnectionString=connectionString;
cmd.CommandText=selectString;
cmd.Connection=cn;
...
}
}
I am having trouble with a simple DELETE statement in SQL with unexpected results , it seems to add the word to the list??. Must be something silly!. but i cannot see it , tried it a few different ways. All the same result so quite confused.
public void IncludeWord(string word)
{
// Add selected word to exclude list
SqlConnection conn = new SqlConnection();
String ConnectionString = "Data Source = dev\\SQLEXPRESS ;" + "Initial Catalog=sml;" + "User id=** ;" + "Password =*;" + "Trusted_Connection=No";
using (SqlConnection sc = new SqlConnection(ConnectionString))
{
try
{
sc.Open();
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'" +
conn);
Command.Parameters.AddWithValue("#word", word);
Command.ExecuteNonQuery();
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
finally
{
sc.Close();
}
ExcludeTxtbox.Text = "";
Box.Text = " Word : " + word + " has been removed from the Exclude List";
ExcludeLstBox.AppendDataBoundItems = false;
ExcludeLstBox.DataBind();
}
Try removing the single quotes. Also why are you concatenating your SQL string with a connection object (.. word='#word'" + conn)???
Try like this:
try
{
using (var sc = new SqlConnection(ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM excludes WHERE word = #word";
cmd.Parameters.AddWithValue("#word", word);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
...
Notice also that because the connection is wrapped in a using block you don't need to Close it in a finally statement. The Dispose method will automatically call the .Close method which will return the connection to the ADO.NET connection pool so that it can be reused.
Another remark is that this IncludeWord method does far to many things. It sends SQL queries to delete records, it updates some textboxes on the GUI and it binds some lists => methods like this should be split in separate so that each method has its own specific responsibility. Otherwise this code is simply a nightmare in terms of maintenance. I would very strongly recommend you to write methods that do only a single specific task, otherwise the code quickly becomes a complete mess.
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'" +
conn);
should be replaced with
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='#word'",
conn);
Also try by removing single quotes as suggested by others like this
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word=#word",
conn);
The #Word should not be in quotes in the sql query.
Not sure why you're trying to add the connection on the end of the sql query either.
To debug this, examine the CommandText on the SqlCommand object. Before reading further, you should try this.
The issue comes with adding the single quotes around a string that is parameterized. Remove the single quotes and life is beautiful. :-)
Oh, and your conn is an object and needs a comma, not a +.
See the code below:
private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("delete successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM supplier";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
See the code below:
String queryForUpdateCustomer = "UPDATE customer SET cbalance=#txtcustomerblnc WHERE cname='" + searchLookUpEdit1.Text + "'";
try
{
using (SqlCommand command = new SqlCommand(queryForUpdateCustomer, con))
{
command.Parameters.AddWithValue("#txtcustomerblnc", txtcustomerblnc.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record Update of Customer...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
You can also try the following if you don't have access to some of the functionality prescribed above (due, I believe, to older versions of software):
using (var connection = _sqlDbContext.CreatSqlConnection())
{
using (var sqlCommand = _sqlDbContext.CreateSqlCommand())
{
sqlCommand.Connection = connection;
sqlCommand.CommandText = $"DELETE FROM excludes WHERE word = #word";
sqlCommand.Parameters.Add(
_sqlDbContext.CreateParameterWithValue(sqlCommand, "#word", word));
connection.Open();
sqlCommand.ExecuteNonQuery();
}
}
...
I'm an associate dev. Hence the "I believe" above.