While I am running the code below, the compiler is giving me the error: "object reference not set to an instance of an object". Please can you tell what mistakes I have made in this code.
public void text()
{
cn1.Open();
string s;
//error came here
s = "select Request_Type from dbo.component where Material_Code='" +
Mcodeddl.SelectedItem.Text + "' ";
//end
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
Just a hunch, but either Mcodeddl or Mcodeddl.SelectedItem is null.
There is probably no selected item in the (assuming) dropdown control.
Add a null check on the Mcodeddl.SelectedItem object before the code with the error to prevent that from happening.
var code = Mcodeddl.SelectedItem.Text; // you may need to check Mcodeddl.SelectedItem != null here, if you not set default selected item
if (string.IsNullOrEmpty(code)) return; // return if code type empty, or show message. depending on your requirement
using (SqlConnection connection = new SqlConnection(connectionString)) // using statement will dispose connection automatically
{
connection.Open();
using (SqlCommand command = new SqlCommand("select Request_Type from dbo.component where Material_Code= #MaterialCode", connection))
{
command.Parameters.AddWithValue("#MaterialCode", code); // use parameters
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var request = reader["Request_Type"];
TextBox4.Text = request != DBNull.Value ? request.ToString().Trim() :string.Empty;// check null before ToString
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
Related
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.
Here's my front end:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.getCodeTypes();
GridView2.DataBind();
}
When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015
Back End:
//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
try
{
OracleConnection con = new OracleConnection(connString);
con.Open();
string query = "select id, descr from code_desc where code_type_id = 0";
// Create the OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
List<CodeDesc> L = new List<CodeDesc>();
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
// Clean up
reader.Dispose();
cmd.Dispose();
con.Dispose();
System.Diagnostics.Debug.WriteLine(L);
return L;
}
catch (Exception ex)
{
// catch clause here...
}
}
CodeDesc:
public class CodeDesc
{
public int id { get; set; }
public string description { get; set; }
}
Any help would be great.
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.
Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block
public List<CodeDesc> getCodeTypes()
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, descr from code_desc where code_type_id = 0";
using(OracleConnection con = new OracleConnection(connString))
using(OracleCommand cmd = new OracleCommand(query, con))
{
con.Open();
// Execute command, create OracleDataReader object
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
}
}
System.Diagnostics.Debug.WriteLine(L);
return L;
}
I have a stored procedure that returns a single record, either null or data if present.
In my code I need to check what that procedure returns. What is the right way to do it?
Now when, running the code I have an exception saying: "Invalid attempt to read when no data is present." I'm using Visual Studio 2005.
Here is my method:
public static String GetRegionBasedOnIso(String isoNum)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
String region = null;
try
{
using (SqlCommand cmd = new SqlCommand("MyProc", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#isoNum", isoNum);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.IsDBNull(0))
{
return null;
}
else
{
region = (String)dr["region"];
}
}
}
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
finally
{
conn.Close();
}
return region;
}
What can I do to fix it? Thank you
if (dr.Read())
{
if (dr.IsDBNull(0))
{
return null;
}
else
{
region = (String)dr["region"];
}
}
else
{
// do something else as the result set is empty
}
I was wondering if someone could help me out with this issue.
Basically I have a Web App, that searches a DB for a person based on an UID. After it finds the name, I open another db conn and search for their Managers email address.
However i'm getting the "Object reference not set to an instance" error, which i'm assuming something is null and it doesn't like it? that correct.
Here is my code.
public partial class Leaver : System.Web.UI.Page
{
string Managers_Name = null;
string Managers_Email = null;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_SearchDB(object sender, EventArgs e)
{
SqlDataReader reader = null;
SqlConnection conn = null;
try
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["App_NewStarterConnectionString"].ConnectionString);
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("SELECT * FROM dbo.tb_starters WHERE Payrol = #Payrol", conn))
{
cmd.Parameters.AddWithValue("#Payrol", Payrol.Value);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Fname.Value = reader["FirstName"].ToString();
Lname.Value = reader["LastName"].ToString();
Payrol.Value = reader["Payrol"].ToString();
section.Value = reader["Section"].ToString();
Managers_Name = reader["Manager"].ToString();
}
}
}
}
catch (Exception ee)
{
throw ee;
}
finally {
GetManagersEmail();
if (reader != null)
reader.Close();
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
protected void GetManagersEmail()
{
SqlDataReader reader_new = null;
SqlConnection conn_new = null;
try
{
conn_new = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["App_NewStarterConnectionString"].ConnectionString);
{
conn_new.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Email FROM dbo.tb_starters WHERE FullName = #ManagersName", conn_new))
{
cmd.Parameters.AddWithValue("#ManagersName", Managers_Name);
while (reader_new.Read())
{
Managers_Email = reader_new["Email"].ToString();
Response.Write(Managers_Email);
}
}
}
}
catch (Exception ee)
{
throw ee;
}
finally
{
if (reader_new != null)
reader_new.Close();
if (conn_new.State == ConnectionState.Open)
conn_new.Close();
}
}
Did you get the reference for reader_new as you did in reader = cmd.ExecuteReader();
try with
reader_new = cmd.ExecuteReader();
However i'm getting the "Object reference not set to an instance" error, which i'm assuming something is null and it doesn't like it? that correct.
Correct. Performing an action on a NULL object throws that error.
Without the stack trace, this is a guess.
Possibly, your error is around here:
Fname.Value = reader["FirstName"].ToString();
Lname.Value = reader["LastName"].ToString();
Payrol.Value = reader["Payrol"].ToString();
section.Value = reader["Section"].ToString();
Managers_Name = reader["Manager"].ToString();
If one of these values is NULL, an Object reference not set to an instance would be thrown.
Don't assign null value to your SqlDataReader and SqlConnection at the begining just define them like
SqlDataReader reader;
SqlConnection conn ;
This might be the problem !!!
I am trying to load data into a textbox by using a DataReader depend on the Drop down list selection. Didn't get error from this code, but the data is not loaded into textbox. please correct me.
public void text()
{
cn1.Open();
string s;
s = "select Request_Type from component where Material_Code='" + Mcodeddl.SelectedItem.Text + "' ";
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
public void MC()
{
Mcodeddl.Items.Clear();
ListItem li1 = new ListItem();
li1.Text = "-Select-";
Mcodeddl.Items.Add(li1);
Mcodeddl.SelectedIndex = 0;
cn1.Open();
string s1;
s1 = "select Material_Code from component";
SqlCommand cd1 = new SqlCommand(s1, cn1);
SqlDataReader dr1;
try
{
dr1 = cd1.ExecuteReader();
while (dr1.Read())
{
ListItem ni1 = new ListItem();
ni1.Text = dr1["Material_Code"].ToString().Trim();
Mcodeddl.Items.Add(ni1);
}
dr1.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
If everything works fine without exceptions that is mean the connection established correctly and the SQL command is correct. I think you have to make sure about your SQL statement. Maybe it returns nothing because there are no matches.
We need more explain about your issue.
I'm using c# in a ASP.Net web application.I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare=14 AND Intrebari.id_intrebare=15 ", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
I want those two values for id_intrebare=14 and 15 to assign it to those 2 labels.How can i refer to those?
In order to read stuff from the reader you need to include it in the select statement for you sql, it is better to select it explicitly rather than use select *.
but you are not currently going to get any results returned because id_intrebare cannot be both 14 and 15
you then need to read id_intreabare ratherr than Intreabari.
Try this, notice the try catch block, I also changed your SQL query.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
string qry="select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare IN (14,15);
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
try
{
con.Open();
SqlDataReader rdr= cmd.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
}
}
catch(SQLException ex)
{
lblStatus.Text="An error occured"+ex.Message;
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to assign texts to different numbered lables in a loop, you can refer to the control id with FindControl of the current page
int numeOrdinal = reader.GetOrdinal("Nume");
int intrebariOrdinal = reader.GetOrdinal("Intrebari");
int i = 1;
while (rdr.Read()) {
// Nume (Romanian) = Name
page.FindControl("lbl" + i).Text = reader.IsDBNull(numeOrdinal)
? ""
: rdr.GetString(numeOrdinal);
// Intrebari (Romanian) = Question
page.FindControl("intrebari" + i + 5).Text = reader.IsDBNull(intrebariOrdinal)
? ""
: rdr.GetString(intrebariOrdinal);
i++;
}
Try using cmd.ExecuteScalar it will return the first reuslt it finds so you have to define your conditions well. Also it returns object type so you will have to cast the result