Thanks for the help in advance.
Im trying to use update query in C#
Error : command is getting executed even if I use incorrect values
Design view
Code :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id='" + TxtEMPID.Text + "' and AvayaID ='" + TxtAvayaID.Text + "'", con);
cmd = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID ='" + TxtAvayaID.Text + "'", con);
cmd.ExecuteNonQuery();
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Successfull";
con.Close();
}
catch (SqlException ex)
{
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Unsuccessfull";
}
your code would look better like this, it not the most optimal, but ia already a way better piece of code then your snippet
1) added parameters using a helper function for the sql injection issue
2) an ExecuteNonQuery returns the rows affected, so if you are expecting that 1 row was updated, you can check on that
3) if you update a row with an id that not exists, it will not throw a SqlException like you are expecting in your code, this happens e.g. when locking occurs
public void Update()
{
var con = new SqlConnection();
try
{
var empId = TxtEMPID.Text
var avayaId = TxtAvayaID.Text
con.Open();
var cmd1 = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id=#empId and AvayaID = #avayaId", con);
cmd1.Parameters.Add(AddParameter("#empId",empId));
cmd1.Parameters.Add(AddParameter("#avayaId", avayaId));
var cmd2 = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID =avayaId", con);
cmd2.Parameters.Add(AddParameter("#avayaId", avayaId));
var rowsaffected1 = cmd1.ExecuteNonQuery();
var rowsAffected2 = cmd2.ExecuteNonQuery();
if (rowsaffected1 == 1 && rowsAffected2 == 1)
{
//success code goes here
//--------
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Successfull";
}
else
{
// failure code goes here
//-----------------------
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Unsuccessfull";
}
}
catch (SqlException ex)
{
//handle errors
}
finally
{
con.Close();
}
Console.ReadLine();
}
private SqlParameter AddParameter(string name, object value) {
var par = new SqlParameter();
par.ParameterName = name;
par.Value = value;
return par;
}
If you put "incorrect" values it just updates zero of records. No errors/exception expected here.
Related
So I know this is a often asked question but I want to check if the username is already taken in the database using c#. I tried this:
MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE(name = '" + tb1.Text + "');");
cmd2.Connection = connect;
connect.Open();
string unt = "";
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
unt= dr.GetString("name");
}
dr.Close();
}
catch (Exception ex)
{
errorbox.Content = ex.Message;
}
finally
{
connect.Close();
}
if(unt == "" || unt == "0") {
continuel = false;
tb2.Text = "User " +tb1.Text+ " doesn't exist!";
Popup1.IsOpen = true;
}
Its a WPF project and the variable 'continuel' is set to true by default. The code doesn't recognize if a user doesn't exist.
First off your code is vulnerable to sql inject, you should never concatenate values into a query. secondly you can do a count and execute a scalar. Not I stripped down your code a little you'll have to add error handling back.
bool userExists = false;
private String sql = "SELECT COUNT(*) FROM tableName WHERE name = #usernameparam;";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("#usernameparam", tb1.Text.Trim());
int userCount = Convert.ToInt32(m.ExecuteScalar());
if(userCount>0)
{
userExists = true;
}
//use userExists variable to evaluate if user exists
I try to updata a single row, chosen by it ID. But what I got at best is an additional row instead of an updated one.
I made several attempts. Now I got a System.InvalidOperationException claiming that a valid InsertCommand is necessary for an update, if a DataRow listing will get a new row.
To me it is the same again: Why insert? I want to update.
Can anybody give me a hint?
This is my related code:
string selectQuery = $"SELECT * FROM Records";
string updateQuery = $"UPDATE Records SET AnyContent = #AnyContent WHERE [ID] = #ID";
OleDbDataAdapter adapter = null;
OleDbCommand cmd = null;
try
{
adapter = new OleDbDataAdapter(selectQuery, ConnectionString);
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = updateQuery;
cmd.Parameters.AddWithValue ("#AnyContent", "066066");
cmd.Parameters.AddWithValue("#ID", 2);
try
{
adapter.UpdateCommand = cmd;
nbRowsChanged = adapter.Update(content);
}
finally
{
adapter?.Close();
cmd?.Close();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
<<< Update >>>
Originally I tried it with an OleDbCommandBuilder before. But CommandBuilder created an update command, which seems to me like an insert command. This is why I tried it without CommandBuilder above. But inserting seems to follow me.
This is my old code, which is closer to where I want to get as it uses a DataTable instead of parameters:
string selectQuery = $"SELECT * FROM Records WHERE [ID] = ?";
OleDbConnection con = null;
OleDbDataAdapter adapter = null;
OleDbCommandBuilder builder = null;
try
{
adapter = new OleDbDataAdapter();
con = new OleDbConnection(ConnectionString);
adapter.SelectCommand = new OleDbCommand(selectQuery, con);
builder = new OleDbCommandBuilder(adapter);
try
{
con.Open();
nbRowsChanged = adapter.Update(content);
logText += "....InsertCommand: " + builder.GetInsertCommand().CommandText + "\n"; // Just to debug
logText += "....UpdateCommand: " + builder.GetUpdateCommand().CommandText + "\n"; // Just to debug
}
finally
{
con?.Close();
adapter?.Dispose();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
logText += tmpText ;
logText += "...Database: Access disposed.\n";
return isSuccess;
And this is the related trace:
LogText:
...Database: Trying to update <1> number of rows in table <Records>
....InsertCommand: INSERT INTO Records (AnyContent) VALUES (?)
....UpdateCommand: UPDATE Records SET AnyContent = ? WHERE ((ID = ?) AND ((? = 1 AND AnyContent IS NULL) OR (AnyContent = ?)))
.... Success: Updated <1> rows.
...Database: Access disposed.
NbRows Before: 5
NbRows After: 6
An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
I have code that inserts data into a table when a user enters certain values into three boxes on the page.
The boxes are order number, total weight and tracking reference.
I now need to add further functionality to this code and check first to see if the order number exists, if it does i need to update the columns, if it doesn't I need to insert a new row and add data to that.
I was thinking simply, something like IF results = 0, Insert NEW, ELSE update
How can I modify my code to do this?
protected void Page_Load(object sender, EventArgs e)
{
errorLabel.Visible = false;
successLabel.Visible = false;
errorPanel.Visible = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
int _orderID = Convert.ToInt32(orderID.Text);
string _trackingID = trackingNumber.Text;
DateTime _date = DateTime.UtcNow;
int _weightID = Convert.ToInt32(weightID.Text);
SqlConnection myConnection = new SqlConnection("Data Source=localhost\\Sqlexpress;Initial Catalog=databasename;User ID=username;Password=password");
SqlCommand myCommand = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
try
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#order", _orderID);
myCommand.Parameters.AddWithValue("#tracking", _trackingID);
myCommand.Parameters.AddWithValue("#date", _date);
myCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
myConnection.Close();
if (rowsUpdated > 0)
{
alertdiv.Attributes.Add("class", "alert alert-success form-signin");
successLabel.Text = "Thank you, tracking details have been updated";
successLabel.Visible = true;
errorPanel.Visible = true;
}
else
{
alertdiv.Attributes.Add("class", "alert alert-error form-signin");
errorLabel.Text = "Oh dear, the order number is not recognised, please check and try again";
errorLabel.Visible = true;
errorPanel.Visible = true;
}
orderID.Text = "";
trackingNumber.Text = "";
weightID.Text = "";
}
catch (Exception f)
{
errorLabel.Text = "This order number does not exist, please check";
errorLabel.Visible = true;
errorPanel.Visible = true;
return;
}
}
}
protected void Signout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
You can add some SELECT query before your INSERT statement. So if the SELECT query returns more than one row, it means that you already have that record in the DB, and need to update. So, in general it will be like
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Shipment WHERE OrderId = #order", myConnection);
cmdCount.Parameters.AddWithValue("#order", _orderID);
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
// UPDATE STATEMENT
SqlCommand updCommand = new SqlCommand("UPDATE Shipment SET TrackingNumber = #tracking, ShippedDateUtc = #date, TotalWeight = #weight", myConnection);
updCommand.Parameters.AddWithValue("#order", _orderID);
updCommand.Parameters.AddWithValue("#tracking", _trackingID);
updCommand.Parameters.AddWithValue("#date", _date);
updCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
}
else
{
// INSERT STATEMENT
SqlCommand insCommand = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
insCommand.Parameters.AddWithValue("#order", _orderID);
insCommand.Parameters.AddWithValue("#tracking", _trackingID);
insCommand.Parameters.AddWithValue("#date", _date);
insCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
}
Edit:
Or much shorter:
SqlCommand command;
if (count > 0)
{
command = new SqlCommand("UPDATE Shipment SET TrackingNumber = #tracking, ShippedDateUtc = #date, TotalWeight = #weight WHERE OrderId = #order", myConnection);
}
else
{
command = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
}
command.Parameters.AddWithValue("#order", _orderID);
command.Parameters.AddWithValue("#tracking", _trackingID);
command.Parameters.AddWithValue("#date", _date);
command.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = command.ExecuteNonQuery();
The most efficient way would be to put the functionality into a Stored Procedure, for instance (pseudo-code):
IF EXISTS(SELECT * FROM Orders WHERE OrderNo = #orderNo)
UPDATE ...
ELSE
INSERT ...
If you cannot create a new stored procedure, you can also create a command that contains this Statement though readability is typically worse.
Both approaches require only one DB-request.
If you like receive all data and check if exist any record use HasRows.
using (SqlConnection connection = new SqlConnection("server name"))
{
SqlCommand cmd = new SqlCommand("select * From Shipment where OrderId =#OrderId", connection);
connection.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows==true)//check have any recorder
{
while (sdr.Read())
{
Debug.Print("Exist recorder, example.: "+sdr["_trackingID"]);
}
}
else
{
Debug.Print("not exist recorder");
}
connection.Close();
}
Below 2 links give the preview of my sample application.
http://img812.imageshack.us/i/image1adl.jpg/ : shows mine sample application. All fields are self explanatory (if query, let me know)
http://img834.imageshack.us/i/image2vc.jpg/ : shows, when clicked the "Edit" button from the grid, the timings are shown correctly but the order gets disturbed. (See 7:00 coming on the top and then the timings list are seen).
My Questions
How to correct the timings problem? (Link # 2)
Code for "Edit" is below
protected void lnkEdit_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt16((sender as Button).CommandArgument);
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE IsDeleted=0 and Imageid='"+ imageid +"'";
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtImageName.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
chkIsActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"].ToString());
ddlStartTime.DataSource = ds;
ddlStartTime.DataTextField = ds.Tables[0].Columns["StartTime"].ColumnName.ToString();
ddlStartTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlStartTime.DataBind();
ddlEndTime.DataSource = ds;
ddlEndTime.DataTextField = ds.Tables[0].Columns["EndTime"].ColumnName.ToString();
ddlEndTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlEndTime.DataBind();
BindDropDownList();
IsEdit = true;
}
When i edit the existing record in the grid, i am getting the values, but the record is not being updated but added as a new record into db. I am aware that i am suppose to write update script. But where to write that?
Below the code is for the same;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string strImageName = txtImageName.Text.ToString();
int IsActive = 1;
if (chkIsActive.Checked)
IsActive = 1;
else
IsActive = 0;
string startDate = ddlStartTime.SelectedItem.Text;
string endDate = ddlEndTime.SelectedItem.Text;
if ( Convert.ToDateTime(endDate) - Convert.ToDateTime(startDate) > new TimeSpan(2, 0, 0) || Convert.ToDateTime(endDate)- Convert.ToDateTime(startDate) < new TimeSpan(2,0,0))
{
//Response.Write(#"<script language='javascript'> alert('Difference between Start Time and End Time is 2 hours'); </script> ");
lblHours.Visible = true;
lblHours.Text = "Difference between Start Time and End Time should be 2 hours";
return;
}
if (checkConflictTime())
{
lblMessage.Visible = true;
lblMessage.Text = "Time Conflict";
return;
}
//if (checkTimeBetween())
//{
//}
if (fuFileUpload.PostedFile != null && fuFileUpload.PostedFile.FileName != "")
{
lblHours.Visible = false;
byte[] imageSize = new Byte[fuFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadedImage = fuFileUpload.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)fuFileUpload.PostedFile.ContentLength);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
SqlCommand cmd = new SqlCommand();
if (IsEdit == false)
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconn;
SqlParameter ImageName = new SqlParameter("#img_name", SqlDbType.NVarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter ActualImage = new SqlParameter("#img_content", SqlDbType.VarBinary);
ActualImage.Value = imageSize;
cmd.Parameters.Add(ActualImage);
SqlParameter DeletedImage = new SqlParameter("#IsDeleted", SqlDbType.Bit);
DeletedImage.Value = 0;
cmd.Parameters.Add(DeletedImage);
SqlParameter IsActiveCheck = new SqlParameter("#IsActive", SqlDbType.Bit);
IsActiveCheck.Value = IsActive;
cmd.Parameters.Add(IsActiveCheck);
SqlParameter StartDate = new SqlParameter("#StartTime", SqlDbType.NVarChar, 100);
StartDate.Value = startDate;
cmd.Parameters.Add(StartDate);
SqlParameter EndDate = new SqlParameter("#EndTime", SqlDbType.NVarChar, 100);
EndDate.Value = endDate;
cmd.Parameters.Add(EndDate);
sqlconn.Open();
int result = cmd.ExecuteNonQuery();
sqlconn.Close();
if (result > 0)
{
lblMessage.Visible = true;
lblMessage.Text = "File Uploaded!";
gvImages.DataBind();
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
}
Please help!
Where do you define Bool/Bolean IsEdit? I think its value is reset on page postback, that's why it is always false and the record is being inserted. I would suggest you to use a hidden field to track this and set its value there and check the value upon insert/updating. Finally it will be something like...
if (ds.Tables[0].Rows.Count > 0)
{
//your code
hiddenField.Value = "true"; // you can set default value to false
}
and then after
if (hiddenField.Value == "false")
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}