update statement error in image - c#

private void btnupdate_Click(object sender, EventArgs e)
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
try
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Update not possible");
}
else
{
cnn.Open();
cmd3.CommandText = "update Slab set indi = #img1 where s_flatno = #s_flatno and s_name = #s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
cnn.Close();
}
}
In this code, I'm updating image in the position indi and I'm setting a new img1 in byte. While press update I'm getting an error
Must declare scalar variable #img1

You have named your variable #img1 in the SQL Statement, but #indi when you declared the variable.
Please note that best practice when handling DBConnection is as a local variable inside a using statement, and you better use one of the overloads of Add when adding parameters to a command instead of AddWithValue. For more information, read Can we stop using AddWithValue() already?
Here is an improved version of your code:
private void btnupdate_Click(object sender, EventArgs e)
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Updation not possible");
}
else
{
try
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
var sql = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
// I'm assuming SQL Server based on the error message
using(var cnn = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#indi", SqlDbType.VarBinary).Value = img1;
cmd.Parameters.Add("#s_flatno", SqlDbType.VarChar).Value = txtfno.Text;
cmd.Parameters.Add("#s_name", SqlDbType.VarChar).Value = txtslab.Text;
}
cnn.Open();
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

There is a small issue with you code. You have not passed #img1 parameter. You are sending it as #indi. Either Change #img1 to #indi in sql query string or change #indi to #img1 in add parameter statement:
cnn.Open();
cmd3.CommandText = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();

Related

System.InvalidOperationException' in System.Data.dll c# making login to the file. sql

im creating e grades project on c#, and i cant normally connect to database. Writing https://i.stack.imgur.com/itJuX.png
Maybe you can help me ? Not working in login.cs. Last job then i do it it was working.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dienynas.mdf;Integrated Security=True;"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
int id = 0;
bool pass = false;
while (sdr.Read())
{
if (sdr[0].ToString() == textBox1.Text && sdr[0].ToString() == textBox2.Text)
{
pass = true;
id = (int)sdr[0];
break;
}
}
if (pass == false)
{
MessageBox.Show("Password for this user is incorrect");
id = (int)sdr[0];
pass = true;
}
else
{
Form1 frm = new Form1(id);
Hide();
frm.Show();
}
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Your problem is in your if statement after the loop.
if (pass == false)
{
MessageBox.Show("Password for this user is incorrect");
id = (int)sdr[0];
pass = true;
}
In that if block you are accessing your SqlDataReader, which very possibly has exited the while loop after returning false upon reading indicating that there is no more data to be read. If there is no data, then you will get an error when attempting to read data that is not there.
I would think that one of the reasons you are exiting the while without ever having a match is that, unless both TextBox1 and TextBox2 contain a matching string you will never have a match. The following line is comparing those text box values to the exact same data value. Unless the text is identical between those text boxes then this statement will always be false.
if (sdr[0].ToString() == textBox1.Text && sdr[0].ToString() == textBox2.Text)
I am guessing that you intended something like this:
if (sdr[0].ToString() == textBox1.Text && sdr[1].ToString() == textBox2.Text)
Edit
With all of that being said, there is a lot of room for refactoring in this code. For one thing, generally performing database operations in a button handler can lead to unresponsive dialog windows and is something to be avoided. You are also using some other objects which are disposable and so you should be cleaning those up as well. I will rewrite the function a little to show you some of the cleanup, but I don't have time to go through splitting it into threads and it is outside the scope of your question.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
try
{
var textBox1 = textBox1.Text;
var textBox2 = textBox2.Text;
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dienynas.mdf;Integrated Security=True;");
conn.Open();
cmd = new SqlCommand("select * from users", conn);
sdr = cmd.ExecuteReader();
int id = -1;
while (sdr.Read())
{
var text0 = sdr[0].ToString();
var text1 = sdr[1].ToString();
// NOTE: You could add the string comparison type here as well
if (text0.Equals(textBox1) && text1.Equals(textBox2))
{
id = (int)sdr[0];
break;
}
}
if (id == -1)
{
MessageBox.Show("Password for this user is incorrect");
}
else
{
Form1 frm = new Form1(id);
Hide();
frm.Show();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sdr?.Dispose();
cmd?.Dispose();
conn?.Dispose();
}
}

C# How to Update/Change the specific letter/number of a string in database

I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID

Retrieve single user data from oracle database into visual studio C# application

I am using forms in visual studio to create an application and then retrieve data from Oracle database. My all parts are working except getting data for the single user. Here is form.cs section for that part
private void getCustomerStringToolStripMenuItem_Click(object sender, EventArgs
e)
{
Getcuststring g = new Getcuststring();
g.Show();
}
This is my partial class named getcuststring.cs
namespace Assignment
{
public partial class Getcuststring : Form
{
public Getcuststring()
{
InitializeComponent();
}
private void Getcuststring_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Getting();
}
public void Getting()
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =" + "(ADDRESS = (PROTOCOL = TCP)" +
"(HOST = *******)(PORT = 1521))" + "(CONNECT_DATA =" + "(SID = dms)));"
+ "User Id= *****;Password= ******;";
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "GET_CUST_STRING_FROM_DB";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("pcustid", OracleDbType.Long).Value = textBox1.Text;
cmd.Parameters.Add("return_value", OracleDbType.Varchar2).Direction = ParameterDirection.ReturnValue;
try
{
cmd.ExecuteNonQuery();
// string result = string.Empty;
var result = cmd.Parameters["result_value"].Value.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
my all other functions are working but when executing this in visual studio it every time give exception out saying no data is found whereas that customer id is present in the Oracle database but it somehow not showing the result but instead raising the exception.
So can u tell me where I am wrong, why he's providing me with an exception saying no data found whereas that data actually exist.
This is the function
CREATE OR REPLACE FUNCTION GET_CUST_STRING_FROM_DB(pcustid NUMBER) RETURN
VARCHAR2 AS
vcustid NUMBER;
vcustname VARCHAR2(255);
vcustsales NUMBER;
vcuststatus VARCHAR2(255);
BEGIN
SELECT CUSTID,CUSTNAME,SALES_YTD,STATUS INTO
vcustid,vcustname,vcustsales,vcuststatus
FROM CUSTOMER
WHERE CUSTID = pcustid;
RETURN 'CustID: ' || vcustid || ' Name: ' || vcustname || ' Status: ' ||
vcuststatus || ' SalesYTD: ' || vcustsales;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20021,'Customer ID not found');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20000,SQLERRM);
END;
I think it is simple typo, line
var result = cmd.Parameters["result_value"].Value.ToString();
should be:
var result = cmd.Parameters["return_value"].Value.ToString();
I built similiar case, and got System.IndexOutOfRangeException when I run it. Correcting typo solved problem. Whole code which worked for me:
OracleConnection CONNECTION
= new OracleConnection("Data Source=XX;User Id=XX;Password=XX;");
CONNECTION.Open();
OracleCommand cmd = new OracleCommand() { Connection = CONNECTION };
cmd.CommandText = "GET_CUST_STRING_FROM_DB";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("pcustid", OracleType.Double).Value = textBox1.Text;
cmd.Parameters.Add("return_value", OracleType.VarChar, 500).Direction
= System.Data.ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
var result = cmd.Parameters["return_value"].Value.ToString();
Console.WriteLine(result);
CONNECTION.Close();

Connect to database in sepaerate method of my SqlCommand

I have a form that checks whether values are in a database before adding them. Each field is in a different table, and to keep everything clean, I have a checkExists method for each field. Is there a way to have a separate method that connects to the database, so that I don't have to connect in every field method?
I'd like to do something like this so that my code is less messy:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
But I get a
local variable set_conn
Argument 2: Cannot Convert from Class_DB to System.Data.SqlClient.SqlConnection
I understand the error, so what can I do to return the correct value, or do I have to establish a connection within my CheckData_Comany() method?
Your method SetConnection should be returning SqlConnection back like:
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
and then you can have something like:
SqlConnection connection = set_conn.SetConnection();
and then pass it in SqlCommand constructor as parameter :
SqlCommand check_Company = new SqlCommand(query_string, connection);
Your complete method implementation would become :
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
and important thing to note is do not forget the close the connection finally by calling connection.Close(), otherwise it might cause eating up the resources that shouldn't happen when we are done with querying the database and we should release the resources occupied.

The ConnectionString property has not been initialized using c# asp.net

Hi i am getting the following error while trying to update my database using c# asp.net.
Error:
Server Error in '/' Application.
The ConnectionString property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
Line 33: catch (Exception e)
Line 34: {
Line 35: throw e;
Line 36: }
Line 37: }
I am explaining my code below.
index.aspx.cs:
protected void reject_Click(object sender, EventArgs e)
{
//LinkButton lbtn = (LinkButton)(sender);
//lbtn.BackColor = System.Drawing.Color.Red;
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
LinkButton lbtn = (LinkButton)grdrow.FindControl("accept");
LinkButton LRejectBtn = (LinkButton)grdrow.FindControl("reject");
// string status = grdrow.Cells[6].Text;
int healthId = int.Parse(lbtn.CommandArgument);
int result=0;
if (Convert.ToString(lbtn.BackColor) == "Color [Green]")
{
char updatedStatus = 'R';
result = objhealthCommentBL.updateStatusDetails(updatedStatus, healthId);
if (result == 1)
{
LRejectBtn.BackColor = System.Drawing.Color.Red;
lbtn.BackColor = System.Drawing.Color.WhiteSmoke;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status has updated successfully.')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status couldnot updated')", true);
}
}
}
healthCommentBL.cs:
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
result = objhealthCommentDL.updateStatusDetails(updatedStatus, healthId);
return result;
}
catch (Exception e)
{
throw e;
}
}
healthCommentDL.cs:
namespace DataAccess
{
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getHealthCommentDetails()
{
try
{
con.Open();
DataSet ds = new DataSet();
string sql = "SELECT Health_Comment_ID,Health_ID,Health_Comment_Name,Health_comment_Email,Health_Comment_Message,Health_Comment_Website,Health_Comment_Status from T_Health_Comment";
sql += " order by Health_Comment_ID ASC ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
con.Close();
con.Dispose();
}
}
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
con.Open();
string query = "UPDATE T_Health_Comment SET Health_Comment_Status = #status WHERE Health_Comment_ID = #healthid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#healthid", healthId);
cmd.Parameters.AddWithValue("#status", updatedStatus);
result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
catch (Exception e)
{
throw e;
}
}
}
}
I am getting the above error in healthCommentBL.cs file in catch statement.Here i can say that the commentstring is properly working in the getHealthCommentDetails method in healthCommentDL.cs file but at the same time it is not working for the 2nd method of this file.Please help me to resolve this error.
When you write your connection as;
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
It will be a field of healthCommentDL class, not a local variable. And it's properties (like ConnectionString) is not initialiazed. Instead of that, define your connections as a local variables in your methods. ADO.NET is pretty good at maintaining your connections as a local variables. Read: SQL Server Connection Pooling
public DataSet getHealthCommentDetails()
{
SqlConnection con = new SqlConnection(CmVar.convar);
and
public int updateStatusDetails(char updatedStatus, int healthId)
{
SqlConnection con = new SqlConnection(CmVar.convar);
A few things more;
You should always use parameterized sql. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.

Categories