I am working on updating gridview value by sending gridview values to other page. Here, I am able to update category dropdown list value and image file only. I am not able to update textbox values.
Here is my code..
Update Product Code:
protected void SubmitButton_Click(object sender, EventArgs e)
{
int productId = Convert.ToInt32(Request.QueryString["ProductID"]);
Product product = new Product();
product.ProductID = productId;
product.ProductName = TitleTextBox.Text;
product.Description = DescriptionTextBox.Text;
product.ItemsInSet = Convert.ToInt32(SetTextBox.Text);
product.UnitPriceOwner = Convert.ToInt32(UnitResellerTextBox.Text);
product.UnitPriceReseller = Convert.ToInt32(UnitResellerTextBox.Text);
product.ShippingCost = Convert.ToInt32(ShipmentTextBox.Text);
product.CategoryID = Convert.ToInt32(CategoryDropDownList.SelectedValue.ToString());
product.Visible = true;
product.InOffer = false;
if (ImageUpload.HasFile)
{
int length = ImageUpload.PostedFile.ContentLength;
product.ProductImage = new byte[length];
ImageUpload.PostedFile.InputStream.Read(product.ProductImage, 0, length);
}
else
{
Byte[] image;
image = ProductBL.GetImage(productId);
product.ProductImage = image;
}
ProductBL.UpdateProduct(product);
MessageLabel.Text = "Product successfully Updated!";
}
UpdateProduct() code:
public static void UpdateProduct(Product product)
{
string query = "UPDATE [Products] SET [ProductName] = #ProductName, [Description] = #Description, [ItemsInSet] = #ItemsInSet, " +
"[UnitPriceOwner] = #UnitPriceOwner, [UnitPriceReseller] = #UnitPriceReseller, [CategoryID] = #CategoryID, " +
"[ShippingCost] = #ShippingCost, [InOffer] = #InOffer, [ProductImage] = #ProductImage, [Visible] = #Visible WHERE [ProductID] = #ProductID";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#ProductName", SqlDbType.Text).Value = product.ProductName;
cmd.Parameters.AddWithValue("#Description", SqlDbType.Text).Value = product.Description;
cmd.Parameters.AddWithValue("#ItemsInSet", SqlDbType.Int).Value = product.ItemsInSet;
cmd.Parameters.AddWithValue("#UnitPriceOwner", SqlDbType.Int).Value = product.UnitPriceOwner;
cmd.Parameters.AddWithValue("#UnitPriceReseller", SqlDbType.Int).Value = product.UnitPriceReseller;
cmd.Parameters.AddWithValue("#CategoryID", SqlDbType.Int).Value = product.CategoryID;
cmd.Parameters.AddWithValue("#ShippingCost", SqlDbType.Int).Value = product.ShippingCost;
cmd.Parameters.AddWithValue("#InOffer", SqlDbType.Bit).Value = product.InOffer;
cmd.Parameters.AddWithValue("#Visible", SqlDbType.Bit).Value = product.Visible;
cmd.Parameters.AddWithValue("#ProductID", SqlDbType.Text).Value = product.ProductID;
cmd.Parameters.Add("#ProductImage", SqlDbType.Image).Value = product.ProductImage == null ? (object)DBNull.Value : product.ProductImage;
DbUtility.UpdateDb(cmd);
}
Page Load Code:
protected void Page_Load(object sender, EventArgs e)
{
int productId = 0;
productId = Convert.ToInt32(Request.QueryString["ProductID"]);
LoadProductDetails(productId);
}
protected void LoadProductDetails(int productId)
{
var product = ProductBL.GetProductById(productId);
TitleTextBox.Text = product.ProductName;
DescriptionTextBox.Text = product.Description;
SetTextBox.Text = Convert.ToInt32(product.ItemsInSet).ToString();
UnitOwnerTextBox.Text = Convert.ToInt32(product.UnitPriceOwner).ToString();
UnitResellerTextBox.Text = Convert.ToInt32(product.UnitPriceReseller).ToString();
ShipmentTextBox.Text = Convert.ToInt32(product.ShippingCost).ToString();
}
Kindly Help me
Try to load your LoadProductDetails in
if(!IsPostback)
{
//here
}
first thing always check for null condition before using Session or Query String variable to avoid any chances of getting error.
I think here you are missing to check !IsPostback condition that's why when you click on Update button then your updated values will be lost as your method LoadProductDetails(productId); called.
Related
Here, when I try to update image in a gridview, I can update everything pretty easily. When I do not select image and try to update other fields, I get above error.
Here is my Code.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int productId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
TextBox productName = GridView1.Rows[e.RowIndex].FindControl("ProductTextBox") as TextBox;
TextBox description = GridView1.Rows[e.RowIndex].FindControl("DescriptionTextBox") as TextBox;
TextBox itemsInSet = GridView1.Rows[e.RowIndex].FindControl("ItemsTextBox") as TextBox;
TextBox unitPriceOwner = GridView1.Rows[e.RowIndex].FindControl("PriceOwnerTextBox") as TextBox;
TextBox unitPriceReseller = GridView1.Rows[e.RowIndex].FindControl("PriceResellerTextBox") as TextBox;
TextBox shippingCost = GridView1.Rows[e.RowIndex].FindControl("CostTextBox") as TextBox;
TextBox inOffer = GridView1.Rows[e.RowIndex].FindControl("InOfferTextBox") as TextBox;
CheckBox visible = GridView1.Rows[e.RowIndex].FindControl("VisibleCheckBox") as CheckBox;
FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
Product product = new Product();
product.ProductID = productId;
product.ProductName = productName.Text;
product.Description = description.Text;
product.ItemsInSet = Convert.ToInt32(itemsInSet.Text);
product.UnitPriceOwner = Convert.ToInt32(unitPriceOwner.Text);
product.UnitPriceReseller = Convert.ToInt32(unitPriceReseller.Text);
product.ShippingCost = Convert.ToInt32(shippingCost.Text);
product.InOffer = Convert.ToBoolean(inOffer.Text);
product.Visible = visible.Checked;
if (FileUpload1.HasFile)
{
int length = FileUpload1.PostedFile.ContentLength;
product.ProductImage = new byte[length];
FileUpload1.PostedFile.InputStream.Read(product.ProductImage, 0, length);
}
else
{
ProductBL.GetImage(productId);
}
ProductBL.UpdateProduct(product);
GridView1.EditIndex = -1;
GridView1.DataSource = ProductBL.GetProducts();
GridView1.DataBind();
}
This is my Business Logic Layer code for Product.
public static void UpdateProduct(Product product)
{
string query = "UPDATE [Products] SET [ProductName] = #ProductName, [Description] = #Description, [ItemsInSet] = #ItemsInSet, " +
"[UnitPriceOwner] = #UnitPriceOwner, [UnitPriceReseller] = #UnitPriceReseller, [CategoryID] = #CategoryID, " +
"[ShippingCost] = #ShippingCost, [InOffer] = #InOffer, [ProductImage] =#ProductImage, [Visible] = #Visible WHERE [ProductID] = #ProductID";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#ProductName", SqlDbType.Text).Value = product.ProductName;
cmd.Parameters.AddWithValue("#Description", SqlDbType.Text).Value = product.Description;
cmd.Parameters.AddWithValue("#ItemsInSet", SqlDbType.Int).Value = product.ItemsInSet;
cmd.Parameters.AddWithValue("#UnitPriceOwner", SqlDbType.Int).Value = product.UnitPriceOwner;
cmd.Parameters.AddWithValue("#UnitPriceReseller", SqlDbType.Int).Value = product.UnitPriceReseller;
cmd.Parameters.AddWithValue("#CategoryID", SqlDbType.Int).Value = product.CategoryID;
cmd.Parameters.AddWithValue("#ShippingCost", SqlDbType.Int).Value = product.ShippingCost;
cmd.Parameters.AddWithValue("#InOffer", SqlDbType.Bit).Value = product.InOffer;
cmd.Parameters.AddWithValue("#Visible", SqlDbType.Bit).Value = product.Visible;
cmd.Parameters.AddWithValue("#ProductID", SqlDbType.Text).Value = product.ProductID;
cmd.Parameters.AddWithValue("#ProductImage", SqlDbType.Image).Value = product.ProductImage;
DbUtility.UpdateDb(cmd);
}
You can check like this before update:
SqlParameter unitsParam = command.Parameters.AddWithValue("#ProductImage", SqlDbType.Image);
if (product.ProductImage == null)
{
unitsParam.Value = DBNull.Value;
}
else
{
unitsParam.Value = product.ProductImage
}
Hi Guys I am trying to understand how to save and edited row to the database
private void BudgetGrid_RowEditEnding(object sender,
DataGridRowEditEndingEventArgs e)
{
SqlCommand gridcmd = new SqlCommand();
SqlConnection rwConn = null;
rwConn = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" + "database=Production; " + "connection
timeout=30");
gridcmd.Connection = rwConn;
rwConn.Open();
//gridcmd.CommandText =
//"SELECT Id, Name, Quantity, Rate, Time FROM Budget";
gridcmd.CommandText =
"UPDATE Budget SET Id = #id, Name = #Name, " +
"Quantity = #Qty, Rate = #Rte WHERE Time = #Time";
SqlDataAdapter gridda = new SqlDataAdapter(gridcmd);
string strId = "#id".ToString();
int intID;
bool bintID = Int32.TryParse(strId, out intID);
string strName = "#Name".ToString();
string strQty = "#Qty".ToString();
int intQty;
bool bintQty = Int32.TryParse(strQty, out intQty);
string strRte = "#Rte".ToString();
int intRte;
bool bintRte = Int32.TryParse(strRte, out intRte);
string strTime = "#Time".ToString();
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#id", SqlDbType.Int));
gridda.SelectCommand.Parameters["#id"].SqlValue = intID;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Name", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Name"].SqlValue = strName;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Qty", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Qty"].SqlValue = strQty;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Rte", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Rte"].SqlValue = strRte;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Time", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Time"].SqlValue = strTime;
DataTable griddt = new DataTable("Budget");
gridda.Fill(griddt);
gridda.UpdateCommand =
new SqlCommandBuilder(gridda).GetUpdateCommand();
BudgetGrid.ItemsSource = griddt.DefaultView;
gridda.Update(griddt);
rwConn.Close();
}
it displays fine. I can edit its but when I click on the other tab it does not update it goes back to the original data.
Most of the code I have been going through its either out dated.. or not what I am looking for.
so here is the database
and here is the app
so basically if i hit tab to the next row. under the event BudgetGrid_RowEditEnding it should update the database.. but now its not.
Just copy below codes. I've created all the thing of you and tested successfully. Rather than the first way, I tried to let you go more popular way. Therefore, it took me time to adopt..
Hope this helps you !
SqlDataAdapter da;
DataTable dt;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = yourConnectionString;
Conn.Open();
SqlCommand gridcomm = new SqlCommand();
gridcomm.Connection = Conn;
gridcomm.CommandText = "SELECT Id, Name, Quantity, Rate, Time FROM Budget";
da = new SqlDataAdapter(gridcomm);
SqlDataReader gridreader = gridcomm.ExecuteReader();
while (gridreader.Read())
{
}
gridreader.Close();
dt= new DataTable("Budget");
da.Fill(dt);
dataGrid_Budget.ItemsSource = dt.DefaultView;
Conn.Close();
}
private void dataGrid_Budget_RowEditEnding(object sender, System.Windows.Controls.DataGridRowEditEndingEventArgs e)
{
DataGridRow editedrow = e.Row;
int row_index = (DataGrid)sender).ItemContainerGenerator.IndexFromContainer(editedrow);
for (int k=0;k< 5;k++)
{
DataGridCell cell = GetCell(row_index, k);
TextBlock tb = cell.Content as TextBlock;
if (k==1)
{
dt.Rows[row_index][k] = tb.Text;
}
else if (k == 4)
{
if (tb.Text != "")
{
dt.Rows[row_index][k] = Convert.ToDateTime(tb.Text);
}
}
else
{
dt.Rows[row_index][k] = Convert.ToInt32(tb.Text);
}
}
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(dt);
}
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
dataGrid_Budget.ScrollIntoView(rowContainer, dataGrid_Budget.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
dataGrid_Budget.UpdateLayout();
dataGrid_Budget.ScrollIntoView(dataGrid_Budget.Items[index]);
row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
Your SQL syntax has to be corrected like,
SqlCommand update_comm = new SqlCommand();
update_comm.Connection = Conn;
update_comm.CommandText = "UPDATE Budget SET id= #u_id, Name= #u_name WHERE person= #psn";
var update_da = new SqlDataAdapter(update_comm);
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_id", SqlDbType.Int));
update_da.SelectCommand.Parameters["#u_id"].Value = yourintvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_name", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#u_name"].Value = yourstringvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#psn", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#psn"].Value = yourstringvalue;
var update_ds = new DataSet();
update_da.Fill(update_ds);
'UPDATE' should be used with 'SET' together.
And if you want to update the actual SQL database with the value of edited rows of DataGrid, please try this.
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(griddt);
SqlConnection uniConn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataTable dt = new DataTable();
uniConn = new SqlConnection(
"server=localhost;" + "Trusted_Connection=yes;" +
"database=Production; " + "connection timeout=30");
cmd = new SqlCommand("UPDATE Budget(id, Name, Quantity, Rate, Time)",
uniConn);
uniConn.Open();
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
BudgetGrid.ItemsSource = dt.DefaultView;
uniConn.Close();
Did you forget to close the connection?
I want to update a cell of the row in gridview. But I am getting error as
ORA-01036: illegal variable name/number
at cmd.ExecuteNonQuery()
Here is my code below:-
protected void SaveChanges(object sender, EventArgs e)
{
myConn.Open();
string excelData = Grid1ExcelData.Value;
string excelDeletedIds = Grid1ExcelDeletedIds.Value;
string[] rowSeparator = new string[] { "|*row*|" };
string[] cellSeparator = new string[] { "|*cell*|" };
string[] dataRows = excelData.Split(rowSeparator, StringSplitOptions.None);
for (int i = 0; i < dataRows.Length; i++)
{
string[] dataCells = dataRows[i].Split(cellSeparator, StringSplitOptions.None);
string mkey = dataCells[0];
string shipName = dataCells[1];
string shipCity = dataCells[2];
string shipAddress = dataCells[3];
string shipCountry = dataCells[4];
string orderDate = dataCells[5];
bool sent = dataCells[6] == "yes";
string insertUpdateQuery = "";
if (!string.IsNullOrEmpty(mkey))
{
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = #ShipName, ShipCity = #ShipCity, ShipAddress = #ShipAddress, ShipCountry = #ShipCountry, OrderDate = #OrderDate, Sent = #Sent WHERE MKEY = #MKEY";
}
else
{
insertUpdateQuery = "INSERT INTO B_Order_new (ShipName, ShipCity, ShipAddress, ShipCountry, OrderDate, Sent) " +
"VALUES(#ShipName, #ShipCity, #ShipAddress, #ShipCountry, #OrderDate, #Sent)";
}
OracleCommand cmd = new OracleCommand(insertUpdateQuery, myConn);
var orderedOn = DateTime.ParseExact(orderDate, "dd/MM/yyyy", null);
cmd.Parameters.Add("#ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("#ShipCity", OracleType.VarChar).Value = shipCity;
cmd.Parameters.Add("#ShipAddress", OracleType.VarChar).Value = shipAddress;
cmd.Parameters.Add("#ShipCountry", OracleType.VarChar).Value = shipCountry;
cmd.Parameters.Add("#OrderDate", OracleType.DateTime).Value = orderedOn;
cmd.Parameters.Add("#Sent", OracleType.Char).Value = true;
if (!string.IsNullOrEmpty(mkey))
{
cmd.Parameters.Add("#MKEY", OracleType.Number).Value = mkey;
}
cmd.ExecuteNonQuery();
if (insertUpdateQuery != "")
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "CloseScript", "alert('Data Updated succesfully');", true);
}
}
if (!string.IsNullOrEmpty(excelDeletedIds))
{
OracleCommand deleteComm = new OracleCommand("DELETE FROM Orders WHERE OrderID IN (" + excelDeletedIds + ")", myConn);
deleteComm.ExecuteNonQuery();
}
myConn.Close();
Grid1.DataBind();
}
The problem is that you are using the wrong bind variable syntax (looks like you're using SQL Server parameter binding syntax). Oracle's ADO.NET provider expects you to use a : prefix rather than a #.
So try something like this instead:
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = :ShipName, ShipCity = :ShipCity, ...
And then when setting the values, you don't need to prefix it:
cmd.Parameters.Add("ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("ShipCity", OracleType.VarChar).Value = shipCity;
...
EDIT
Also, if you are binding the parameters by name, make sure you set the OracleCommand.BindByName property to true. Otherwise, the binding will be done positionally.
I am unable to update record in my database.
my code is as follows:
private void update_Click(object sender, EventArgs e)
{
con.Open();
try
{
string strQuery = "UPDATE test_name SET Test_Name = #name, Price = #price, Lab_Price = #lprice, normal_value_child = #child, normal_value_men = #men, normal_value_women = #women, notes = #note, unit = #un, SubGroup = #sub, MainGroup = #main" +
"WHERE Test_Id = #tstID";
using (System.Data.SqlServerCe.SqlCeCommand cmdSelect = new System.Data.SqlServerCe.SqlCeCommand(strQuery, con))
{
cmdSelect.Parameters.AddWithValue("#tstID", richTextBox2.Text);
cmdSelect.Parameters.AddWithValue("#name", richTextBox1.Text);
cmdSelect.Parameters.AddWithValue("#price", richTextBox7.Text);
cmdSelect.Parameters.AddWithValue("#lprice", richTextBox8.Text);
cmdSelect.Parameters.AddWithValue("#child", richTextBox5.Text);
cmdSelect.Parameters.AddWithValue("#men", richTextBox4.Text);
cmdSelect.Parameters.AddWithValue("#women", richTextBox3.Text);
cmdSelect.Parameters.AddWithValue("#note", richTextBox9.Text);
cmdSelect.Parameters.AddWithValue("#un", richTextBox6.Text);
cmdSelect.Parameters.AddWithValue("#sub", comboBox2.Text);
cmdSelect.Parameters.AddWithValue("#main", comboBox1.Text);
cmdSelect.ExecuteNonQuery();
updatedb();
con.Close();
}
}
catch (Exception ex)
{
}
this.test_nameTableAdapter2.Fill(this.datalabDataSet14.test_name);
MessageBox.Show("Updated Successfully");
}
}
I don't understand what's the problem.
Add space before WHERE:
string strQuery = "UPDATE test_name SET Test_Name = #name, Price = #price, Lab_Price = #lprice, normal_value_child = #child, normal_value_men = #men, normal_value_women = #women, notes = #note, unit = #un, SubGroup = #sub, MainGroup = #main" +
" WHERE Test_Id = #tstID";
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";
}