My delete has the same issue where it says
no value given for one or more parameters
I actually don't know the code to fix this.
This is what I have atm:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string FirstName = txtFirstName.Text;
sql = " DELETE FROM Club_Member WHERE FirstName = #FirstName; ";
dbCmd = new OleDbCommand(sql, dbConn);
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
string FirstName = txtFirstName.Text;
sql = " DELETE FROM Club_Member WHERE FirstName = #FirstName; ";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd .Parameters.Add(new OleDbParameter("#FirstName",FirstName ));
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
Isn't that obvious?
You declared #FirstName parameter in your SqlCommand but you never add a value as a parameter.
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.AddWithValue("#FirstName", FirstName);
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection dbConn = new OleDbConnection(ConnString))
using(OleDbCommand dbCmd = dbConn.CreateCommand())
{
dbCmd.CommandText = "DELETE FROM Club_Member WHERE FirstName = #FirstName";
dbCmd.Parameters.AddWithValue("#FirstName", FirstName);
dbConn.Open();
dbCmd.ExecuteNonQuery();
}
I always prefer to use Add method instead of AddWithValue because AddWithValue method sends nvarchar type since it is a string variable. But in some cases, you don't want this. You want to declare your SqlDbType as well.
For example, if you have a varchar column and you used AddWithValue method, ADO.NET send it as an nvarchar value and that might cause potential information lost. (for non-Latin characters for example)
This happens mainly because of the Miss spelled values or if you leave any values blank while entering or adding. So database confuses it with a parameter. Debug or just check for spelling.
BTW I wanted to know what is primary key you are using for Club_Member?
Related
I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.
I'm performing a command to erase data from a DataGridView
But I can not make it work, I just want to select a line and erase it
In addition to programming a button that says "Delete" so that when you click on it, the selected data in the DataGridView will be deleted
I need really help
I am lost
My Table is "Person"
My Column is "ID"
Instances
{SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt;}
public string Del(int ID)
{
string ouk = "Delete Work";
try
{
cmd = new SqlCommand("Delete From Person Where = ID )", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
return ouk;
}
For Button Erase at DataGridView
private void buttondel_Click(object sender, EventArgs e)
{
MessageBox.Show(c.Del(TBID));
}
The issue is that your SQL query is malformed and that you're not passing the ID to the query:
"Delete From Person Where = ID )"
One side of the equality check is missing, and you have an unexpected closing bracket.
You should change your query to accept a parameter:
"Delete From Person Where ID = #id"
and then pass the parameter to your command:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
So it becomes:
try
{
using (cmd = new SqlCommand("Delete From Person Where ID = #id", cn))
{
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
I've taken the liberty of wrapping SqlCommand in a using statement so that it's disposed once we're done with it.
Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
OleDbConnection con = new OleDbConnection(strConnString);
string strQuery = "INSERT INTO image([FileName],[FilePath],[AlbumName]) Values(#FN, #FP, #AN)";
OleDbCommand cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#FN", FileName);
cmd.Parameters.AddWithValue("#FP", "images/" + FileName);
cmd.Parameters.AddWithValue("#AN", txtAlbumname.Text.ToString());
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string var = DropDownList1.SelectedItem.ToString();
txtAlbumname.Text = var.ToString();
}
}
I Have tried almost everything , but this error keeps on coming.
I have put on the brackets aswell incase of reserved words but still this error is showing
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
For Example
OleDbCommand command = new OleDbCommand(queryString, connection);
command.CommandText =
"SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
command.Parameters.Add(parameters);
for (int j=0; j<parameters.Length; j++)
{
command.Parameters.Add(parameters[j]) ;
}
for reference ..
MSDN
IMAGE is a reserved word in Access SQL so to use it as a table name you must also enclose it in square brackets:
string strQuery = "INSERT INTO [image] ([FileName], ...
I am using the follwing code to update a person's email and password in the db. I have a datagridview which has only one row. When I hit the Update button, nothing happens - the page is refreshed and the values in the textboxes go back to what they were before....the update is not working. Please help. Thanks!
protected void btnUpdateAccount_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "UPDATE Member SET [Email] = #email, [Password] = #password WHERE [MemberID] = '" + mem_id + "'";
TextBox email = email = (TextBox)Gridview1.Rows[0].FindControl("user_email");
TextBox password = (TextBox)Gridview1.Rows[0].FindControl("user_password");
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters.Add("#password", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = email.Text;
cmd.Parameters["#password"].Value = password.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error: ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
cmd.ExecuteNonQuery();
it return an integer value, so you can put.
int i = cmd.ExecuteNonQuery();
and see what it is returning, also you can use finally after catch to make sure the db con is closed. here you are just using it in the catch, also try to put break point and see if the parameter are passed in correct way and follow it till the end.
like
finally
{
if (con != null)
{
con.Close();
}
}
You need to bind the data from database again to get the new changes. grid view .bind()
There are a number of things that could be happening.
1) The btnUpdateAccount_Click event is never raised. To fix this, make sure the asp:Button tag has an OnClick="btnUpdateAccount_Click" attribute set.
An exception is being thrown and that you're not noticing.
The database is being updated, but you did not load/bind the data again to display the updated values.
Make sure to put in your PageLoad Clause
** Change Made **
As per #marc_s comment changed if(this.IsPostBack == true) to if(this.IsPostBack)
this.IsPostBack is boolean.
if(this.IsPostBack)
{
//dont load page
}