This question already has answers here:
How to execute a stored procedure within C# program
(14 answers)
Closed 4 years ago.
I am Getting the error while executing the code, CommandText Property has been not initialized
public DataTable Mappingdataload(string name)
{
try
{
string spname = "";
switch (name.ToLower())
{
case "student":
spname = "RetrieveStudent";
break;
case "organization":
spname = "RetrieveOrganization";
break;
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = SQLConClass.GetSQLConnection();
cmd.CommandText = spname;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception)
{
throw;
}
}
you are getting this error because command text is not initialized :)
It is always better to first make connection and then create command. check the code below.
var conn = SQLConClass.GetSQLConnection();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
also better to use it like this:
using (var conn = SQLConClass.GetSQLConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;
using (var reader = cmd.ExecuteReader())
{
....
}
}
Related
My query will execute the first time in a switch case loop, but during the second case nothing happens with it
everything is written inside of a for loop, it manages to add the first query into the database properly but after that it doesn't
string sQuery = string.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}',{10}", sName, sMiddleName, sSurname, sBirthdate, sSex, sNationality, sDateOfArrival, sCardID, sUsername, sPassword, sPhoneNumber);
SqlConnection cnn;
cnn = new SqlConnection(Globals.sqlConnect);
cnn.Open();
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
for (int i = 0; i < 2; i++)
{
switch (i)
{
case 0:
sql = "INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES(" + sQuery + ")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
break;
case 1:
if (Properties.Settings.Default.HoF == true)
{
sQuery = string.Format("'{0}' ,{1}",Properties.Settings.Default.Familyname,tb_cardID);
sql = "INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES ("+ sQuery +")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
}
break;
Since I didn't know where the values for the parameters came from I just assumed they were passed into the procedure. You need to check the datatypes of the of the parameters in your database and change the code accordingly. Convert the values to matching types. using blocks ensure that your database objects are closed and disposed even if there is an error. Using parameters protects you form Sql injection.
The loop ,switch and dataadapter are unnecessary.
private void OPCode(string sName,string sMiddleName,string sSurname,DateTime sBirthdate,string sSex,string sNationality,DateTime sDateOfArrival,int sCardID,string sUsername,string sPassword,string sPhoneNumber, int tb_cardID)
{
using (SqlConnection cnn = new SqlConnection(Globals.sqlConnect))
{
using (SqlCommand command = new SqlCommand("INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES (#sName, #sMiddleName, #sSurname, #sBirthdate, #sSex, #sNationality, #sDateOfArrival, #sCardID, #sUsername, #sPassword, #sPhoneNumber);", cnn))
{
command.Parameters.Add("#sName", SqlDbType.VarChar).Value = sName;
command.Parameters.Add("#sMiddleName", SqlDbType.VarChar).Value = sMiddleName;
command.Parameters.Add("#sSurname", SqlDbType.VarChar).Value = sSurname;
command.Parameters.Add("#sBirthdate", SqlDbType.DateTime).Value = sBirthdate;
command.Parameters.Add("#sSex", SqlDbType.VarChar).Value = sSex;
command.Parameters.Add("#sNationality", SqlDbType.VarChar).Value = sNationality;
command.Parameters.Add("#sDateOfArrival", SqlDbType.DateTime).Value = sDateOfArrival;
command.Parameters.Add("#sCardID", SqlDbType.Int).Value = sCardID;
command.Parameters.Add("#sUsername", SqlDbType.VarChar).Value = sUsername;
command.Parameters.Add("#sPassword", SqlDbType.VarChar).Value = sPassword;
command.Parameters.Add("#sPhoneNumber", SqlDbType.VarChar).Value = sPhoneNumber;
cnn.Open();
command.ExecuteNonQuery();
} //disposes command
if (Properties.Settings.Default.HoF == true)
{
using(SqlCommand command = new SqlCommand("INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES (#FamilyName, #tb_carID;", cnn))
{
command.Parameters.Add("#Familyname", SqlDbType.VarChar).Value = Properties.Settings.Default.Familyname;
command.Parameters.Add("#tb_cardID", SqlDbType.Int).Value = tb_cardID;
command.ExecuteNonQuery();
}//disposes second command
}
}//closes and disposes connection
}
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 keep getting this error
There is already an open datareader associated with this command which must be closed first.
at this line of code:
using (SqlDataReader rd = command.ExecuteReader())
I have tried to close all other SqlDataReader's in class but it didn't work.
public int SifreGetir(string pEmail) {
SqlCommand command = con.CreateCommand();
command.CommandText = #"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=#email";
command.Parameters.Add("#email", SqlDbType.VarChar);
command.Parameters["#email"].Value = pEmail;
using (SqlDataReader rd = command.ExecuteReader())
{
rd.Read();
string pass = rd["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
}
Try implementing your code in the below format
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("your sql command", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
}
}
}
The using statement will ensure disposal of the objects at the end of the using block
try this:
public int SifreGetir(string pEmail) {
SqlConnection con = new SqlConnection("Your connection string here");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand command = new SqlCommand(#"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=#email",con);
command.CommandType = CommandType.Text;
command.Parameters.Add("#email", SqlDbType.VarChar).Value = pEmail;
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
string pass = dr["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
con.Close();
}
You have used Using Keyword for SQL Reader but There is nothing to take care of your command and connection object to dispose them properly. I would suggest to try disposing your Connection and command both objects by Using keyword.
string connString = "Data Source=localhost;Integrated " + "Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new;
cmd.CommandText = "SELECT ID, Name FROM Customers";
conn.Open();
using (SqlDataReader rd = command.ExecuteReader())
{
rd.Read();
string pass = rd["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
}
I created the below method which i tested and does return the correct data. Where I am confused is what is the proper way to populate individual textboxes on a form with the results from this method?
Rather than using an objectdatasource and then binding a gridview to the objectdatasource that works but I need more freedom to customize the form.
public MemberDetails GetMemberDetail(int membershipgen)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("usp_getmemberdetail", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#MEMBERSHIPGEN", SqlDbType.Int, 5));
cmd.Parameters["#MEMBERSHIPGEN"].Value = membershipgen;
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
reader.Read();
MemberDetails mem = new MemberDetails((int)reader["MEMBERSHIPGEN"], (string)reader["MEMBERSHIPID"], (string)reader["LASTNAME"],
(string)reader["FIRSTNAME"], (string)reader["SUFFIX"], (string)reader["MEMBERTYPESCODE"]);
reader.Close();
return mem;
}
catch (SqlException err)
{
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
Something along the lines of:
var memberDetails = GetMemberDetail(12345);
textBox1.Text = memberDetails.Prop1;
textBox2.Text = memberDetails.Prop2;
...
Also I would refactor this method and make sure that I properly dispose disposable resources by wrapping them in using statements to avoid leaking unmanaged handles:
public MemberDetails GetMemberDetail(int membershipgen)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "usp_getmemberdetail";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MEMBERSHIPGEN", membershipgen);
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (reader.Read())
{
return new MemberDetails(
reader.GetInt32(reader.GetOrdinal("MEMBERSHIPGEN")),
reader.GetString(reader.GetOrdinal("MEMBERSHIPID")),
reader.GetString(reader.GetOrdinal("LASTNAME")),
reader.GetString(reader.GetOrdinal("FIRSTNAME")),
reader.GetString(reader.GetOrdinal("SUFFIX")),
reader.GetString(reader.GetOrdinal("MEMBERTYPESCODE"))
);
}
return null;
}
}
}
Get the MemberDetails;
var memberDetails = GetMemberDetail(1);
Populate the textbox;
TextBox.Text = memberDetails.Property;
Jawaid outside of the correct answers that were provided below I would also set SqlConnection con = null; and
SqlCommand cmd = null; outside the try and inside the try put the following
con = new SqlConnection(connectionString);
this way if there is an Error when doing cmd.Parameters.Add -- you can trap that exception
also dispose of the reader object
if (reader != null)
{
((IDisposable)reader).Dispose();
// somthing like that .. do the same for con and cmd objects or wrap them in a using() {}
}
cmd = new SqlCommand("usp_getmemberdetail", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#MEMBERSHIPGEN", SqlDbType.Int, 5));
cmd.Parameters["#MEMBERSHIPGEN"].Value = membershipgen;