ASP.net c# Database call - c#

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 !!!

Related

Best way to create new SqlConnection when is null

I have two methods that connect to the database and I try to avoid double code
one of my methods is one that can run alon (open itself SqlConnection and close it)
another method using existing SqlConnection and using SqlTransaction also (I don't want to open another connection and also I don't want to close it)
my first method :
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
using (SqlConnection openCon = new SqlConnection(connectionString))
{
string query = "SELECT [CSeriesNum],[CCount],[Mark] from [Serieses] " +
"where [TestPrimary]=#deliveryNumber";
SqlCommand command = new SqlCommand(query, openCon);
command.Parameters.AddWithValue("#deliveryNumber", DeliveryReportObject.DeliveryNumber);
openCon.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
CSerieses.Add(new CSerieses(reader.GetString(0), reader.GetInt32(1), reader.GetBoolean(2)));
}
}
openCon.Close();
}
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}
The method that using on the transaction :
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject,
SqlConnection co,SqlTransaction tran)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
using (co)
{
string query = "SELECT [CSeriesNum],[CCount],[Mark] from [Serieses] " +
"where [TestPrimary]=#deliveryNumber";
SqlCommand command = new SqlCommand(query, co, tran);
command.Parameters.AddWithValue("#deliveryNumber", DeliveryReportObject.DeliveryNumber);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
CSerieses.Add(new CSerieses(reader.GetString(0), reader.GetInt32(1), reader.GetBoolean(2)));
}
}
}
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}
I try to combine them :
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject,
SqlConnection co = null,SqlTransaction tran = null)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
using (co ?? new SqlConnection(connectionString))
{
if (co.IsOpened() == false)
{
co.Open();
}
string query = "SELECT [CSeriesNum],[CCount],[Mark] from [Serieses] " +
"where [TestPrimary]=#deliveryNumber";
SqlCommand command = new SqlCommand(query, co, tran);
if(tran != null)
{
command.Transaction = tran;
}
command.Parameters.AddWithValue("#deliveryNumber", DeliveryReportObject.DeliveryNumber);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
CSerieses.Add(new CSerieses(reader.GetString(0), reader.GetInt32(1), reader.GetBoolean(2)));
}
}
}
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}
It does not work for me. I have no idea how to check if it null in using and if yes to create a new instance of SqlConnection that should close at the end of the using statement
And I do it the right way anyway?
This is a major problem:
using (co ?? new SqlConnection(connectionString))
If co is passed in, then you don't own it - the caller does - so: you shouldn't be disposing it. What I would suggest here is:
bool ownConnection = false;
try
{
if (co is null)
{
ownConnection = true;
co = new SqlConnection(...);
co.Open();
}
// your code here
}
finally
{
if (ownConnection)
{
co?.Dispose();
}
}
or wrap that up in a helper - perhaps a custom disposable that takes a connection and connection string:
public readonly struct ConnectionWrapper : IDisposable
{
private readonly bool owned;
public SqlConnection Connection { get; }
public ConnectionWrapper(SqlConnection connection, string connectionString)
{
if (connection is null)
{
owned = true;
Connection = new SqlConnection(connectionString);
Connection.Open();
}
else
{
owned = false;
Connection = connection;
}
}
public void Dispose()
{
if (owned)
{
Connection?.Dispose();
}
}
}
then you can just use:
using var wrapped = new ConnectionWrapper(co, connectionString);
// your code, using wrapped.Connection
This seems that kind of situation that perfectly fits the overload concept.
The GetCSerieses method should have two versions, the first one builds its own connection and transaction, the second one takes both a non optional connection and a non optional transaction. The first one, after creating the connection and the transaction calls the second one.
Now if a third method requires a call the GetCSerieses could pass its own connection and transaction, while a call without them will be handled by the first overload
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject)
{
using(SqlConnection con = new SqlConnection(......))
{
try
{
con.Open();
using(SqlTransaction tran = con.BeginTransaction())
{
return GetCSerieses(DeliveryReportObject, con, tran);
}
// Or, if you don't need a transaction you could call the
// overload passing null
// return GetCSerieses(DeliveryReportObject, con, null);
}
catch(Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
return null; // ?? or return new List<CSerieses>();
}
}
}
public static List<CSerieses> GetCSerieses(DeliveryReportObject DeliveryReportObject, SqlConnection co, SqlTransaction tran)
{
List<CSerieses> CSerieses = new List<CSerieses>();
try
{
// We don't own the connection and the transaction object.
// Whoever passed them to us is responsible of their disposal.
string query = "......";
SqlCommand command = new SqlCommand(query, co, tran);
command.Transaction = tran;
....
}
catch (Exception ex)
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
return CSerieses;
}

Combobox not filling from database C#

I'm trying to fill a combo box on from load from a database, I'm getting the error "Invalid object name 'POOL'"
Form load event to populate dropdown on form load
private void FRMAddTeam_Load(object sender, EventArgs e)
{
if (CMBBXPool.Items.Count > 0)
CMBBXPool.Items.Clear();
Database.CLSDB DatabaseClass = new Database.CLSDB();
DatabaseClass.FillDropDownList();
}
This is the code in my database connection class
public void FillDropDownList()
{
string PoolName = "";
Team.FRMAddTeam TeamAdd = new Team.FRMAddTeam();
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
Code to add the pool name
public void addPoolItem(string PoolName)
{
CMBBXPool.Items.Add(PoolName);
}
Any help is much appreciated
Your code needs to be:
public void FillDropDownList(Team.FRMAddTeam TeamAdd)
{
string PoolName = "";
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
You call it from your form like this:
DatabaseClass.FillDropDownList(this);
This will work, however it is strongly advised to change the implementation of your database class and remove tight coupling with GUI.
It is WRONG to fill your GUI from database class - instead of that, you should return data from your database class and bind your data to GUI in the GUI class.
http://en.wikipedia.org/wiki/Loose_coupling
http://en.wikipedia.org/wiki/Object_orgy
http://en.wikipedia.org/wiki/Separation_of_concerns
Sounds like you dont have table Pool.Are you sure its there?
Log into your SQL management studio and use query analyzer to run the same command.
There could be many reasons for that If your schema is different or do you have permission to access that table ? or are you checking the right database ?
UPDATE:
You should try using SELECT [Name] FROM dbo.TBL_Pool

Have trouble reading a null returned from stored procedure

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
}

Handling multiple buttons in same asp.net page

hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx

C# command execution error for data reader

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);
}

Categories

Resources