NullReferenceException: Object reference not set to an instance of an object.
WebApplication1.Controllers.LabsDal.GetDefinition(string connectionString, string key) in LabsDal.cs on line while (rdr2.Read())
conn.Open();
using (var cmd = new SqlCommand("Lab_GetDefinitionList", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#key", key);
SqlDataReader rdr2 = cmd.ExecuteReader(System.Data.CommandBehavior.SingleResult);
while (rdr2.Read()) // <---- ERROR HERE
{
result.Elements.Add(rdr2.GetString(0));
}
}
I have tried many variation and have made no progress. Else where the equivalent code is working fine.
You need to check for IsDBNull:
rdr2.Read()
if(rdr2.HasRows)
{
if(!rdr2.IsDBNull(colIndex))
result.Elements.Add(rdr2.GetString(colIndex));
}
Or you can use SqlDataAdapter :
using (SqlCommand cmd = new SqlCommand())
{
DataSet ds = new DataSet();
cmd.Connection = new SqlConnection(connectionString);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 900;
cmd.CommandText = "Lab_GetDefinitionList";
cmd.Parameters.AddWithValue("#key", key);
cmd.Connection.Open();
//
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
cmd.Connection.Close();
// **check if return data**
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
result.Elements.Add(ds.Tables[0].Rows[0]["YourColumnName"].ToString());
}
for checking null ,try this:
if(rdr2.HasRows)
{
if(!rdr2.IsDBNull(colIndex))
result.Elements.Add(rdr2.GetString(colIndex));
}
Related
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.
This question already has answers here:
Error: Procedure or function expects parameter which was not supplied
(2 answers)
Closed 5 years ago.
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("#CallType", SqlDbType.VarChar).Value = ddlCalltype.SelectedValue.ToString();
cmd.Parameters.Add("#Format", SqlDbType.VarChar).Value = ddlFormat.SelectedValue.ToString();
cmd.Parameters.Add("#disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedValue.ToString();
cmd.Parameters.Add("#SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedValue.ToString();
cmd = new SqlCommand("UserManagement", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
gvDetails.DataSource = dt;
gvDetails.DataBind();
gvDetails.Visible = true;
Your code is a big mess. To me it looks like you've just used copy and paste from a bunch of other places and don't quite really understand what's going on in there.
It should be something like this:
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
DataTable dt = new DataTable();
using(var con = new SqlConnection(strConnString))
{
using(var cmd = new SqlCommand("UserManagement", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CallType", SqlDbType.VarChar).Value = ddlCalltype.SelectedValue.ToString();
cmd.Parameters.Add("#Format", SqlDbType.VarChar).Value = ddlFormat.SelectedValue.ToString();
cmd.Parameters.Add("#disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedValue.ToString();
cmd.Parameters.Add("#SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedValue.ToString();
using(var da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(dt);
}
}
}
gvDetails.DataSource = dt;
gvDetails.DataBind();
gvDetails.Visible = true;
This line assigned new instance of SqlCommand to cmd for second time instead of using existing SqlCommand which contains declared parameters, therefore removing all parameters already declared above:
cmd = new SqlCommand("UserManagement", con);
The correct way to manage SqlCommand with parameterized stored procedure should be like this, with using statement to manage system resources during execution (better to use try...catch...finally block in case you want to handle SqlException):
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
var dt = new DataTable();
using (var con = new SqlConnection(strConnString))
{
con.Open();
using (var cmd = new SqlCommand("UserManagement", con))
{
cmd.Parameters.Add("#CallType", SqlDbType.VarChar).Value = ddlCalltype.SelectedValue.ToString();
cmd.Parameters.Add("#Format", SqlDbType.VarChar).Value = ddlFormat.SelectedValue.ToString();
cmd.Parameters.Add("#disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedValue.ToString();
cmd.Parameters.Add("#SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedValue.ToString();
cmd.CommandType = CommandType.StoredProcedure;
// using SqlDataAdapter
using (var da = new SqlDataAdapter)
{
da.SelectCommand = cmd;
da.Fill(dt);
}
// using DataTable.Load directly
// dt.Load(cmd.ExecuteReader());
}
con.Close();
}
// other stuff
NB: In short you can replace the second assignment of cmd in question using cmd.CommandText = "UserManagement";, hence it just supplying stored procedure name instead assigning another instance of SqlCommand. Also instead of ExecuteNonQuery() try using ExecuteReader() with DataTable.Load() method.
I have this simple code:
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sqlStatement, con))
{
con.Open();
cmd.CommandTimeout = commandTimeOut;
cmd.CommandType = isStoredProcedure ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null) //there are parameters to this query
{
foreach (string key in parameters.Keys)
cmd.Parameters.AddWithValue(key, parameters[key]);
}
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
return ds;
Is it possible to do it parallel?
Hi My Static Method is
[WebMethod(EnableSession = true)]
public static List<Entity.Report> ChartNavigation(string type, string user, string date)
{
WebForm2 objForm = new WebForm2();
objForm.BindCVTrackerForNavigation(user, date);
List<Entity.Report> listchart = new List<Entity.Report>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Recruitment"].ConnectionString))
{
string sqlString = "GetNumberOfCVSentForChartNavigation";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserName", user.Replace("\"", "")));
cmd.Parameters.Add(new SqlParameter("#Date", date.Replace("\"", "")));
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
Entity.Report obj = new Entity.Report();
Utilities.Common.Fill(obj, rdr);
listchart.Add(obj);
}
conn.Close();
}
}
return listchart;
}
And I am calling Non static method from it. My non static method is
protected void BindCVTrackerForNavigation(string User,string Date)
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Recruitment"].ConnectionString))
{
string sqlString = "GetNumberOfCVSentForNavigation";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserName", User.Replace("\"", "")));
cmd.Parameters.Add(new SqlParameter("#Date", Date.Replace("\"", "")));
conn.Open();
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(ds);
conn.Close();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
gvCVTracker.DataSource = ds.Tables[0];
gvCVTracker.DataBind();
}
}
}
}
When datasource is apply to gvCVTracker it throws error Object reference not set to an instance of an object. I dont know what is the problem? Any help would be appriciated.Thanks.
You must use Page.LoadControl to create an instance of the WebForm2 for it to also process the initialization of the controls.
How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}