I have been created student details page.
Here is my code for update:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("sp_updatestudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
com.Parameters.AddWithValue("#Email", Textemail.Text.Trim());
com.Parameters.AddWithValue("#Mobilenum", Textmobilenum.Text.Trim());
com.Parameters.AddWithValue("#EC_id", Textcurricular.SelectedValue);
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
foreach (string f in files) File.Delete(f);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
}
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
The insertion works fine., when i edit the row from gridview and doing some changes and update, the updated row is not working.
After insertion the row in grid view like this: screenshot-1
after edit and update the row same in gridview like this: screenshot-2
so what is my mistake in my update code?
Can anyone guide me to fix this?
Thanks,
Related
enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}
I have been created student details form by using aspx and c#.
In the image field i got some error.
What i have done:
Insert,edit and update image.
When i insert image and submit, I was set to display that image in gridview on the same page, and also save in "images" folder in my drive.
It works fine, but when i edit the image and upload new image and submit, the changed image didn't show in the gridview, but this changed image saved in "images" folder.
May i know, what is my mistake in my code?
Here is my source code:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("sp_updatestudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
string uniqueFileName = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
foreach (string f in files) File.Delete(f);
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : (uniqueFileName.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
}
else
{
SqlCommand com = new SqlCommand("sp_insertstudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
try
{
string filename = string.Empty;
string uniqueFileName = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
}
}
Here is editrow:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
Image1.ImageUrl = ((System.Web.UI.WebControls.Image)gr.Cells[7].Controls[0]).ImageUrl;
}
}
and here is my output of my screenshot:
http://s3.postimg.org/bpgzjlmub/untitled.jpg
Can anyone help me to fix my issue, I'm new to .net.
Any help would be highly appreciated.
The gridview in asp.net does not automatically update itself. You need to again bind the gridview. What you need to do is put the code of binding the grid in one function say bindgrid() something like this.
public void bindgrid()
{
con = new SqlConnection(connStr);
con.Open();
da = new SqlDataAdapter("select * from Grid_Data", con);
Dataset ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
and then call bindgrid() after every insert and update performed in grid. If this doesn't work out, I might need to see your binding logic.
Thank you
I am creating student records using c# and asp .net. For this, I added 5 fields - name, class, section, address and image.
When inserting student1.jpg, it works fine. Problem appears When I insert second record for same name (student1.jpg) with different image. Insertion fails with some error like "image already exists".
After I understood the purpose of GUID, I want to use these for my work.
Is it possible to do so and if yes, can someone help me?
Here is my full code-behind file:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
if (File.Exists(Server.MapPath("~/Images/" + filename)))
{
Label6.Visible = true;
return;
}
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
}
Thank you.
Namespace: using System.IO;
For StoredProdure3:
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower(); // this will give you file extension.
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension; // this will give you unique filename.
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName)); // save the image with guid name.
com.Parameters.AddWithValue("#Image",(filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty); // now you can save the new filename in database for associated record.
}
For StoredProdure1:
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
if (File.Exists(Server.MapPath("~/Images/" + filename)))
{
Label6.Visible = true;
return;
}
string fileExtension = Path.GetExtension(filename).ToLower(); // this will give you file extension.
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension; // this will give you unique filename.
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName)); // save the image with guid name.
}
com.Parameters.AddWithValue("#Image",(filename.Length > 0)? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
Now all uploaded images that will be saved to drive will have unique name even if original filename is same but images are different.
Assuming that Id is the primary key on your table, then just replace
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
with
com.Parameters.AddWithValue("#id", System.Guid.NewGuid().ToString());
If this doesn't resolve your issue, I could assist further if you provided the structure of your table, or the code in your stored procedure.
--EDIT--
With your edits, my answer no longer makes sense as we now know that varchar isn't acceptable as id and the error is being thrown at the point of the fileupload.SaveAs().
Suprabhat Biswal is on the right track as you should be using GUID to be changing your file name.
Here's some updated code, NOTE that i changed the id back to the Textid.Text.Trim().
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
var filename = string.Format("{0}.{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileupload.PostedFile.FileName).ToLower());
var full_path = Server.MapPath("~/Images/", filename);
if (fileupload.PostedFile.FileName.Length > 0)
{ ;
fileupload.SaveAs(full_path);
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
var filename = string.Format("{0}.{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileupload.PostedFile.FileName).ToLower());
var full_path = Server.MapPath("~/Images/", filename);
// This IF statement should never be hit since we're using GUID for the file name.
if (File.Exists(full_path))
{
Label6.Visible = true;
return;
}
fileupload.SaveAs(full_path);
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
}
If i understood your problem:
These changes are enough with your original code for use of GUID.
make change in db table "Student" for column Id from "int" to "NVARCHAR(36)"
Form Code behind Pass "Id" parameter values as
string ID = Guid.NewGuid().ToString();
com.Parameters.AddWithValue("#id", ID);
you can keep image name as original name.
OR------
U can directly genarat GUID in DataBase also as follows
ALTER PROCEDURE StoredProcedure3
(
#Name Varchar (100),
#Class varchar (50),
#Section Varchar (50),
#Address Varchar (50),
#Image Varchar (50)
)
AS
begin
DECLARE #id NVARCHAR(36);
SET #id = NEWID();
Update Student set Name = #Name, Class= #Class, Section= #Section, Address = #Address, Image = #Image where id=#id
End
I have been created upload image with edit and update.
When i insert image it will be stored both in hard drive and database.
If edit and upload another and click update, it will changed in gridview. but also i want to delete if already uploaded image in hard drive.
Here is my full source:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string filepath = #"E\student\student\student\Images";
if (Directory.Exists(Path.GetDirectoryName(filepath)))
{
File.Delete(filepath);
}
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#Address", Textaddress.Text.Trim());
try
{
string filename = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
com.Parameters.AddWithValue("#Image",(filename.Length>0)? "Images/" + filename:string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
Response.Redirect("studententry.aspx");
}
}
May i know, how to delete if already uploaded image in the hard drive?
Any help would be highly appreciated.
Thanks,
Comment this code, is useless as well as wrong, SaveAs will overwright the file
string filepath = #"E\student\student\student\Images";
if (Directory.Exists(Path.GetDirectoryName(filepath)))
{
File.Delete(filepath);
}
if you really really want to delete:
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
if(File.Exists(Server.MapPath("~/Images/" + filename)))
File.Delete(Server.MapPath("~/Images/" + filename));
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
edit again:
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
foreach(string f in files) File.Delete (f);
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
}
For data access layer:
Source:
public string insert_details(bisuness_object user_details)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tbl_rgsthome values(#firstname,#lastname,#emailid,#password,#address,#upload)", con);
try
{
cmd.Parameters.AddWithValue("#firstname", user_details.firstname_value);
cmd.Parameters.AddWithValue("#lastname", user_details.lastname_value);
cmd.Parameters.AddWithValue("#emailid", user_details.emailid_value);
cmd.Parameters.AddWithValue("#password", user_details.pass_value);
cmd.Parameters.AddWithValue("#address", user_details.addr_value);
cmd.Parameters.AddWithValue("#upload", user_details.fileupl_value);
//cmd.Parameters.AddWithValue("#imagepath", user_details.imgpth_value);
return cmd.ExecuteNonQuery().ToString();
}
catch (Exception show_error)
{
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
home.aspx:
public string getimage(object ob)
{
string img = #"/image/" + ob.ToString();
return img;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
bisuness_object bo = new bisuness_object();
// cmd.Parameters.AddWithValue("#imagepath", ("#uploadimage") + filename);
bo.firstname_value = TextBox1.Text;
bo.lastname_value = TextBox2.Text;
bo.emailid_value = TextBox3.Text;
bo.pass_value = TextBox4.Text;
bo.addr_value = TextBox6.Text;
bo.fileupl_value = FileUpload1.FileName.ToString();
bisuness_layer bl = new bisuness_layer();
bind();
try
{
string result = bl.record_insert(bo);
}
catch (Exception info)
{
throw info;
}
finally
{
bo = null;
bl = null;
bind();
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
}
}
how to solve it.....please help me
i want to image in gridview
bind the image tag inside the gridview dynamically
by giving the path dynamically
<asp:Image ID="image" Style="width:100px; height:100px;" runat="server" ImageUrl='<%# "~/folder/subfolder/" + Eval("id") +"."+ Eval("imagetype") %>' />
and the method for binding the gridview
protected void GetDayoffer()
{
gridview1.DataSource = bl.method();
gridview1.DataBind();
}
hope this will help you or recovert the bytes into image again and bind it into gridview