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.
Related
I have this code running in form_load event:
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("pp_sp_MachineAndOp", sqlConn);
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
sqlDa.Fill(sqlDt);
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
sqlDa.Dispose();
sqlConn.Close();
}
I get error 'Procedure or function 'pp_sp_MachineAndOp' expects parameter '#MachineAndOpID', which was not supplied.' at line:
sqlDa.Fill(sqlDt);
Important to say that if I open DataTable Visualizer of sqlDt at runtime I see expected results!
Here is a code behind Helper.ExecuteDataTable:
public static DataTable ExecuteDataTable(string storedProcedureName, params SqlParameter[] arrParam)
{
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
try
{
sqlConn.Open();
// Define the command
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcedureName;
// Handle the parameters
if (arrParam != null)
{
foreach (SqlParameter param in arrParam)
{
sqlCmd.Parameters.Add(param);
}
}
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
{
da.Fill(dt);
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dt;
}
What I am missing?
Remove everything except
DataTable sqlDt = Helper.ExecuteDataTable("pp_sp_MachineAndOp", new SqlParameter("#MachineAndOpID", 7));
dgvMachineAndOp.AutoGenerateColumns = false;
dgvMachineAndOp.DataSource = sqlDt;
your Helper.ExecuteDataTable is doing everything. you don't need to replicate same this in your code.
I think your helper class is creating connection with database as your data table has data.
So, try to remove stored proc name and connection object from adaptor and then check.
SqlDataAdapter sqlDa = new SqlDataAdapter();//use this only.
you can use below function(modification required as per your need):
public IDataReader ExecuteReader(string spName, object[] parameterValues)
{
command = GetCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = spName;
if (parameterValues != null)
{
for (int i = 0; i < parameterValues.Length; i++)
{
command.Parameters.Add(parameterValues[i]);
}
}
reader = command.ExecuteReader();
if (parameterValues != null)
command.Parameters.Clear();
return reader;
}
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));
}
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.
I got two classes, one for db connection and another to get data. When I use the SqlCommand type as stored procedure it returns the data table properly, but when I change the command type to text and change the command text properly it returns a null value. Why is this happening?
Class 1
public class DB_Connection
{
public SqlConnection cnn;
public SqlCommand cmd;
public SqlDataAdapter ada;
public DB_Connection()
{
cnn = new SqlConnection("Data Source=svr01;Initial Catalog=PDFScramble;Integrated Security=True");
cnn.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;// *changed in here SP or Text*
cmd.Connection = cnn;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
}
Class 2
public class Data : DB_Connection
{
public string DException { get; set; }
public DataTable Datatable { get; set; }
public bool GetCivicEntities()
{
try
{
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
ada.Fill(Datatable);// *Null in here*
return true;
}
catch (Exception ex)
{
DException = ex.Message;
return false;
}
}
Your Datatable is null, because of that you have this problem. This should fix it.
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
Datatable = new DataTable();
ada.Fill(Datatable);
return true;
There is something wrong with the class structure. Check with this
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("SPName", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("select * from dummy",conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}
Thanks to some tips and reminders here, I changed my code from this kludgy mess:
try
{
DataSet dsUsage = new DataSet();
SqlConnection conn = new SqlConnection("SERVER=PROSQL05;DATABASE=platypusdata;UID=duckbill;PWD=poisonToe42;Connection Timeout=0");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = String.Format("Exec sp_ViewProductUsage_MappingRS '{0}', '{1}', '{2}'", mammal, dateBegin, dateEnd);
da.SelectCommand = cmd;
conn.Open();
da.Fill(dsUsage);
conn.Close();
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
...to this:
try
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet dsUsage = new DataSet();
using (SqlConnection conn = new SqlConnection(UsageRptConstsAndUtils.PlatypusConnStr))
{
using (SqlCommand cmd = new SqlCommand("sp_ViewProductUsage_MappingRS", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Unit", SqlDbType.VarChar).Value = _unit;
cmd.Parameters.Add("#BegDate", SqlDbType.DateTime).Value = dtBegin;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = dtEnd;
da.SelectCommand = cmd;
conn.Open();
//cmd.ExecuteReader(); <- Is this even necessary?
da.Fill(dsUsage);
}
}
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
// Populate the cells
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
Note that I have SqlCommand's ExecuteReader commented out in the new code because it seems unnecessary due to the SqlDataAdapter being provided the SqlCommand. It works fine. So: am I correct in assuming I can remove cmd.ExecuteReader() altogether? Is there any benefit in retaining it, or would that be totally redundant and create "busy work" for the process?
UPDATE
So, to pass an array of SqlParameter (to the ExecuteDataSet method in MethodMan's answer), I take it that I would first have to do something like:
SqlParameter sqlp = new SqlParameter();
sqlp.ParameterName = "Unit";
sqlp.Value = _unit;
cmd.Parameters.Add(sqlp);
...etc. (and then add them to an array - or, possibly better a generic list of SqlParameter).
UPDATE 2
I just ran into this for the first time: if you use MethodMan's example (which I do) and you use a parameterless query, you need to bypass the parameter-adding loop like so:
if (null != parameters)
{
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
}
I would personally create a SqlDBHelper class and pass call the stored procedure using a method such as this
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
//log to a file or write to Console for example
Console.WriteLine(ex.Message);
}
return ds;
}
}
}
If you want to return a DataTable then change the return type in the Method signature and call the following in the return statement below
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
return ds.Tables[0];
Here is an example on how you would call the method
someDataTable = SqlDBHelper.ExecuteDataSet("sp_ViewProductUsage_MappingRS", CommandType.StoredProcedure,
new SqlParameter() { ParameterName = "#Unit", SqlDbType = SqlDbType.VarChar, Value = _unit },
new SqlParameter() { ParameterName = "#BegDate", SqlDbType = SqlDbType.DateTime, Value = dtBegin },
new SqlParameter() { ParameterName = "#EndDate", SqlDbType = SqlDbType.DateTime, Value = dtEnd }
);