I can't extract the values through a query and insert them into textboxes
Where am I going wrong?
Request.QueryString.Get("ID_Persona");
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID","");
cmd.Parameters.AddWithValue("#Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("#Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("#Email", TextBox20.Text);
cmd.Parameters.AddWithValue("#CodiceFiscale", TextBox22.Text);
con.Open();
cmd.ExecuteNonQuery();
}
You need to use ExecuteReader to read values, something like this:
var connectionString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
//IDTextBox? = rdr["Id"].ToString(),
TextBox1.Text = rdr["Nome"].ToString(),
TextBox15.Text = rdr["Cognome"].ToString(),
TextBox20.Text= rdr["Email"].ToString(),
TextBox22.Text= rdr["CodiceFiscale"].ToString(),
}
}
}
}
You should use a ExecuteReader() instead of ExecuteNonQuery() since ExecuteNonQuery is meant for DML operations. Again, you need only the ID value to be passed then why you are passing unnecessary parameters to your query. Remove them all. An example below
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader["Email"]));
}
I can see several issues:
You should use ExecuteReader() instead of ExecuteNonQuery()
You should provide just 1 parameter - #ID; I doubt if it should have an empty value.
You should wrap IDisposable into using
Code:
string query =
#"SELECT ID,
Nome,
Cognome,
Email,
CodiceFiscale
FROM Persona
WHERE ID = #id";
using (SqlConnection con = new SqlConnection(...))
{
con.Open();
using SqlCommand cmd = new SqlCommand(query, con)
{
// I doubt if you want empty Id here.
// I've assumed you want to pass ID_Persona
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
TextBox1.Text = Convert.ToString(reader["Nome"]);
TextBox15.Text = Convert.ToString(reader["Cognome"]);
TextBox20.Text = Convert.ToString(reader["Email"]);
TextBox22.Text = Convert.ToString(reader["CodiceFiscale"]);
}
}
}
}
Related
I'm trying to get the UserName and put it in TempData but I get an error when the code reaches the ExecuteReader() method.
Here's my query code:
var InvoiceId = TempData["newinvoice"];
TempData["invoiceid"] = InvoiceId;
var UserID = TempData["UserID"];
string connection = "Data Source=.;Initial Catalog=project;Integrated Security=true;";
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = new SqlCommand("SELECT UserName FROM AspNetUsers WHERE Id = #id"))
{
sqlcomm.Parameters.Add("#id", SqlDbType.VarChar).Value = UserID;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sqlcomm.Connection = sqlconn;
sqlconn.Open();
sda.SelectCommand = sqlcomm;
SqlDataReader sdr = sqlcomm.ExecuteReader();
while (sdr.Read())
{
TempData["UserId"] = sdr["UserName"];
}
}
}
}
The User Id from TempData["UserID"] is an nvarchar(450) not an integer. I have no clue why that exception is happening - any help?
Note: here's an example from one of my user ids:
'aa776084-053e-452c-8b0d-b445cdbf457d'
It looks like your id is a uniqueidentifier and if so I would recommend changing your database and code to use GUIDs.
However to fix your problem, you should be able to pass in the UserId and call toString() (as the value is most likely an object) e.g:
sqlcomm.Parameters.Add("#id", SqlDbType.NVarChar, UserID.ToString());
If you're only going to return one results, maybe use ExecuteScalar()
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = new SqlCommand("SELECT TOP 1 UserName from AspNetUsers where Id=#id", sqlconn)
{
sqlcomm.Parameters.Add("#id", SqlDbType.NVarChar, UserID.ToString());
object result = sqlcomm.ExecuteScalar();
if (result != null)
{
TempData["UserId"] = result.ToString(); // It looks like you're mixing UserId & UserName .
}
}
}
I'm displaying some data from the database into textboxes on my windows form and I have to add something else but it depends on the account type (that information is saved on my Databse). Meaning it is either DM (domestic) or CM(comercial). I want for it to charge an extra amount if it's CM.
I would appreciate any help, thank you.
OracleDataReader myReader = null;
OracleCommand myCommand = new OracleCommand("SELECT SUM(IMPORTE) AS corriente FROM MOVIMIENTOS WHERE CUENTA='"+txtIngreseCuenta3.Text + "'AND CONCEPTO=10", connectionString);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtCorriente.Text = (myReader["corriente"].ToString());
}
I'm using this code to display into the textbox but I want it to get the account type from another table and IF it's CM then add a certain amount into a textbox.
In your case I suggest that you use Execute Scalar instead of reader since you are returning only one value from the database. but in your case if you want this code to work you need to Cast the returned value into the correct dot net type and then populate the TextBox.
Example Using ExecuteReader
//txtCorriente.Text = ((int)myReader["corriente"]).ToString();
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtCorriente.Text = ((int)reader["corriente"]).ToString();
txtAnother.Text = ((decimal)reader["another"]).ToString();
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Example Using ExecuteScalar
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
Am trying to populate a listbox with values generated by a query, the code runs without any problems but the listbox is not displaying any results, what am i doing wrong, is there anything missing??
String sql = "SELECT * FROM products where code = "+textBox1.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn); //c.con is the connection string
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
listBox1.Items.Add(reader["description"].ToString() + ": "+reader["price"].ToString());
listBox1.Refresh();
}
reader.Close();
conn.Close();
}
}
If your code column is of string type then
String sql = "SELECT * FROM products where code = '"+textBox1.Text + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn); //c.con is the connection string
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
listBox1.Items.Add(reader["description"].ToString() + ": "+reader["price"].ToString());
}
reader.Close();
}
conn.Close();
}
Also to add all values, use while instead of if to traverse all the records in the reader. And also close the connection after the using statement.
I am sure the wrong sequence is causing the issue.
I'm making some assumptions here about your code, is 'code' a number? If not, did you try:
String sql = "SELECT * FROM products where code = '"+textBox1.Text+"'";
?
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;
}
}
Can anybody give an example for executing a T-SQL statement using C#?
Do you mean something like this:
private static void ReadOrderData(string connectionString)
{
string commandText = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
}
}
Or, perhaps something like:
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#Name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
Source: MSDN
I suggest that you start with an ADO.NET turorial like this one
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
How to use SQLCommand
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson03.aspx
Using a reader:
SqlConnection MSSQLConn = new SqlConnection("your connection string");
MSSQLConn.Open();
SqlCommand MSSQLSelectConsignment = new SqlCommand();
MSSQLSelectConsignment.CommandText = "select * from yourtable where blah = #blah";
MSSQLSelectConsignment.Parameters.AddWithValue("#blah", somestring);
MSSQLSelectConsignment.Connection = MSSQLConnOLD;
SqlDataReader reader = MSSQLSelectConsignment.ExecuteReader();
while (reader.Read())
{
...
}
To bring back a single value:
MSSQLSelectConsignment.CommandText = "select fieldname from yourtable where blah = #blah";
string yourstring = MSSQLSelectConsignment.ExecuteScalar().ToString();
or to bring back number of rows affected for updates etc:
MSSQLSelectConsignment.CommandText = "update yourtable set yourfield = 0 where blah = #blah";
int yourint = MSSQLSelectConsignment.ExecuteNonQuery();
Hope helps :)