I have prepared this Form to upload a book to the server side db with its image.
I have to read and retrieve the book on another page thus saving image path in database and also saving image in a folder "upload" ..
I tried debugging the code, problem is that the debug arrow does not even enters the button click event.
On designing section, there's just a simple form comprising of textboxes retrieving client's information on book and also a file upload controller, within same button click event.
public partial class UploadBooks : System.Web.UI.Page
{
string strcon = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// add session name
//Label3.Text = Session["StudFirstName"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
// image uploading
if (FileUpload1.HasFile)
{
try
{
if (FileUpload1.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload1.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Uploads") + filename);
Label2.Text = "Upload status: File uploaded!";
}
else
Label2.Text = "Upload status: The file has to be less than 100 kb!";
}
else
Label2.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
Label2.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Insert into Books (StudId,BookId,Title,Author,Description,Price,Owner,Phone_no,ImagePath) values (#sid,#bid,#t,#a,#d,#p,#o,#n,#i)", con);
cmd.Parameters.AddWithValue("#sid", Label4.Text);
cmd.Parameters.AddWithValue("#bid", Label1.Text);
cmd.Parameters.AddWithValue("#t", TextBox1.Text);
cmd.Parameters.AddWithValue("#a", TextBox2.Text);
cmd.Parameters.AddWithValue("#d", TextBox3.Text);
cmd.Parameters.AddWithValue("#p", TextBox6.Text);
cmd.Parameters.AddWithValue("#o", TextBox4.Text);
cmd.Parameters.AddWithValue("#n", TextBox5.Text);
cmd.Parameters.AddWithValue("#i", FileUpload1.FileName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("1 Book Added");
}
}
}
Based on your clarification in the comment it is clear that you are trying to INSERT a value into the table's IDENTITY column.
Most likely it is the StudId or the BookID column.
Remove the identity column from your cmd.Parameters.AddWithValue() statement and your INSERT string and you should be good.
SQL Automatically inserts this value and increments it based on the previous values.
If your IDENTITY column is StudId then your insert string should look like:
"Insert into Books (BookId,Title,Author,Description,Price,Owner,Phone_no,ImagePath) values (#bid,#t,#a,#d,#p,#o,#n,#i)"
If your IDENTITY column is BookId then it should look like:
"Insert into Books (StudId,Title,Author,Description,Price,Owner,Phone_no,ImagePath) values (#sid,#t,#a,#d,#p,#o,#n,#i)"
Then just delete the cmd.Parameters.AddWithValue() line for the related parameter.
Related
I'm creating a windows application using C# whereby I'm accessing an empty Access database which contains two tables: Provinces and Locations. I'm working on the form that just deals with the Provinces table which looks like this:
This is a subform. When it is open, I can insert/update records etc. Whenever I make a change, I click on the Load Table button to display the changes in the DataGridView object.
If I close this subform and show it again, I can click on the Load Table button and recall all the data for display in the DataGridView object. However, if I close down the application altogether, then I lose all my data. I prove this by double clicking the database file to launch it in Access where I can see that the data is definitely gone. This has become a mystery as I can't figure out why the data doesn't persist in the file. Please advise.
Below is the code for the form. You can see from my methods that I'm careful to close the connection object each and every time I perform a function. So I'm at a loss as to why I keep losing the data on application close?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GTI_Taxi_Pricing
{
public partial class frmProv : Form
{
private OleDbConnection connection = new OleDbConnection();
public frmProv()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TaxiDB.accdb;Persist Security Info=False;";
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
String query = "SELECT * FROM Provinces;";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtName.Text == "")
{
MessageBox.Show("The name field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Provinces (name) VALUES ('" + txtName.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnNewRecord_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtName.Text = "";
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
{
MessageBox.Show("The id field must have a value.");
return;
}
if(txtName.Text == "")
{
MessageBox.Show("The name field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "UPDATE Provinces SET name='" + txtName.Text + "' WHERE id=" + txtID.Text + ";";
command.ExecuteNonQuery();
MessageBox.Show("Data Update Successful.");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
{
MessageBox.Show("The id field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "DELETE FROM Provinces WHERE id=" + txtID.Text + ";";
command.ExecuteNonQuery();
MessageBox.Show("Record Deleted Successfully.");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(e.RowIndex >= 0)
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
txtID.Text = row.Cells[0].Value.ToString();
txtName.Text = row.Cells[1].Value.ToString();
}
}
}
}
This is a common scenario with file based database (or attached database files)
Your connection string refers to the database without using any path.
This means that your database is located in the same directory where your application runs.
You don't have any problem inserting, modifying or deleting data but you loose everything when you restart the app from INSIDE a Visual Studio Debug Session.
Now, if you look at your project files you probably have the database file listed between the other files. Between the properties of this database file you will notice the property Copy to the Output directory and its value set to Copy Always.
This means that every time you restart your application from inside the Visual Studio environment that file is copied from the project folder to the output directory (usually BIN\DEBUG or BIN\x86\DEBUG) but this destroys the database used in the previous run removing the data inserted modified or deleted
Change the property Copy to Output Directory to Copy Never or Copy if Newer
However Copy If Newer presents another problem with MS-Access. If you open the database file located in your project directory using Access o using the Server Connection window of Visual Studio the file is immediately modified also if you don't change anything and thus the Copy If Newer will execute the copy to the output directory
protected void upimg_about_Click(object sender, EventArgs e)
{
con.Open();
string sqlQuery = " UPDATE [dbo].[tbldetails] SET [image]=#image,[image2]=#image2 WHERE id=#id";
SqlCommand cmd2 = new SqlCommand(sqlQuery, con);
cmd2.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = Image1.PostedFile.ContentLength;
int img2 = Image2.PostedFile.ContentLength;
byte[] msdata = new byte[img];
byte[] msdata2 = new byte[img2];
Image1.PostedFile.InputStream.Read(msdata, 0, img);
Image2.PostedFile.InputStream.Read(msdata2, 0, img2);
cmd2.Parameters.AddWithValue("#image", msdata);
cmd2.Parameters.AddWithValue("#image2", msdata2);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd2.ExecuteNonQuery();
con.Close();
data1.Text="Image Updated Successfully";
}
This is the code I am using to update the images in the database.
The user when required can update the images (eg: in the firstpage.aspx) and can retrieve it in the next page (nextpage.aspx).
But the problem is: suppose a user wants to update just a single image and he/she upload's the image and clicks the update button and when retrieving images in the next page the image that was updated is visible but the one which is already present in the database is not. I am not sure but during the updation the other fileupload is empty is this why this is happening? Is there other way to do it?
PS: I have textboxes in the firstpage.aspx in which i am retrieving the text he/she has already put in the database and hence when the user wants to make changes it can be done easily.
TextBox1.Text = dr["name"].ToString();
TextBox2.Text = dr["address"].ToString();
So, is it possible to retrieve the image path which the user has previously submitted? Or any way in which the user can update a single image and during retrieval both the images can be retrieved?
Thank You! :)
Break your code up so that you can send 1 image at a time to the DB. Then pass the corresponding FileUpload and SQL Column name to your function. Conditionally send the new file to the database depending on whether the FileUpload contains a file. You can check this by looking at the HasFile property.
protected void upimg_about_Click(object sender, EventArgs e)
{
// make sure at least 1 file
if (!Image1.HasFile && !Image2.HasFile)
{
data1.Text="No Images Uploaded";
return;
}
con.Open();
UploadImage(Image1, "[image]");
UploadImage(Image2, "[image2]");
con.Close();
data1.Text = "Image Updated Successfully";
}
void UploadImage(FileUpload fileUpload, string columnName)
{
if (!fileUpload.HasFile)
{
return;
}
string sqlQuery = "UPDATE [dbo].[tbldetails] SET " + columnName + "=#image WHERE id=#id";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = fileUpload.PostedFile.ContentLength;
byte[] msdata = new byte[img];
fileUpload.PostedFile.InputStream.Read(msdata, 0, img);
cmd.Parameters.AddWithValue("#image", msdata);
cmd.ExecuteNonQuery();
}
I've tried a few things I've read on StackOverflow with some other topics with no success.
public partial class Content_Management : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Code fires EVERY TIME a Row is selected in the Gridview control
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//Extract upload Title and assign to relevant Textbox control
TextBox1.Text = GridView1.SelectedRow.Cells[2].Text.ToString();
//Extract upload album name and assign to relevant Textbox control
TextBox3.Text = GridView1.SelectedRow.Cells[3].Text.ToString();
//Extract upload Image and assign to relevant Image control
Image4.ImageUrl = "~/uploadedimages/" + GridView1.SelectedRow.Cells[5].Text.ToString();
//Extract upload Status and assign to DropDownList control
DropDownList1.Text = GridView1.SelectedRow.Cells[8].Text.ToString();
//Enable the "Update" Button control
Button2.Enabled = true;
//Extract upload Multimedia Clip and load into MediaPlayer control ready for playing
Media_Player_Control1.MovieURL = Server.MapPath("~/uploaded_multimedia/" + GridView1.SelectedRow.Cells[5].Text.ToString());
}
//This code will execute EVERY TIME "Save" Button is clicked
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Birdspotting"].ConnectionString);
//Then I would reference the string e.g
//Create variable to point to image upload folder
string image_folder = Server.MapPath("~\\uploadedimages\\");
//Create 2 variables and set the file names to blank in case User does not upload any files - DB entries will still be made
string dbfilename1 = "";
string dbfilename2 = "";
//Check if the Image Fileupload control has a file or not
if (FileUpload1.HasFile)
{
//If the Fileupload control has a file, change the value of the variable to the selected image file name
string filename1 = FileUpload1.FileName.ToString();
//Copy the selected Image file from the Users device accross the Internet and save it into the Image folder within the Web App structure
FileUpload1.SaveAs(image_folder + filename1);
//Assign the new file name to the variable used to populate the DB - change from "" to actual file name
dbfilename1 = filename1;
}
//Repeat as above for Multimedia Clip - audio or video
string multimedia_folder = Server.MapPath("~\\uploaded_multimedia\\");
if (FileUpload2.HasFile)
{
string filename2 = FileUpload2.FileName.ToString();
FileUpload2.SaveAs(multimedia_folder + filename2);
dbfilename2 = filename2;
}
//Create DB Connection - point to SQL
// create sql connection object. make sure to put a valid connection string
SqlCommand cmd = new SqlCommand("Insert into LeagueTable" + "(BirdName, Quantity, ArtworkImage, MediaClip, Username, Datetime, ActiveStatus, UserId)"
+ "Values(#1, #2, #3, #4, #5, #6, #7, #8) Select SCOPE_IDENTITY()");
//SqlXml newXml = new SqlXml(new XmlTextReader("Birds.xml"));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
//Define the structure of the SQL Statement - used to executed instructions against the DB Table
//The DB Table name and each field is indentified in the command.
//INSERT commands includes Primary Key insertion -that is generated by the DB itself
cmd.Parameters.AddWithValue("#1", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#2", TextBox3.Text.ToString());
cmd.Parameters.AddWithValue("#3", dbfilename1.ToString());
cmd.Parameters.AddWithValue("#4", dbfilename2.ToString());
cmd.Parameters.AddWithValue("#5", User.Identity.Name);
cmd.Parameters.AddWithValue("#6", DateTime.Now.ToString());
cmd.Parameters.AddWithValue("#7", DropDownList1.Text.ToString());
cmd.Parameters.AddWithValue("#8", System.Data.SqlDbType.Int);
cmd.Connection = conn;
try
{
conn.Open();
var added = cmd.ExecuteNonQuery();
lblConfirm.Text = added.ToString() + "Record Inserted.";
}
catch (Exception ex)
{
lblError.Text = "Error Inserting Record";
lblError.Text += ex.Message;
}
finally
{
conn.Close();
}
GridView1.DataBind();
}
}
I have a DataGridView which displays 3 rows, when I try to update my records it says successfully changed the records. But when I check the database the records were not updated.
And in the delete button it says I must select a record to delete but I already selected a row in my DataGridView
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace RFG_Inventory_and_Management_System
{
public partial class AdminForm : Form
{
SqlCommand cmd;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\Visual Studio 2010\Projects\RFG Inventory and Management System\RFG Inventory and Management System\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommandBuilder cmdbl;
SqlDataAdapter adap;
DataSet ds;
int ID = 0;
public AdminForm()
{
InitializeComponent();
PayratesDisplay();
NonMemberDisplay();
}
//Display Data in DataGridView
private void PayratesDisplay()
{
con.Open();
DataTable dt = new DataTable();
adap = new SqlDataAdapter("select * from tbl_payrates", con);
adap.Fill(dt);
dataGridView4.DataSource = dt;
con.Close();
}
private void NonMemberDisplay()
{
con.Open();
DataTable dt = new DataTable();
adap = new SqlDataAdapter("SELECT tbl_nonMember.*, tbl_customer.lname, tbl_customer.fname, tbl_customer.mname, tbl_customer.gender, tbl_customer.age, tbl_customer.membership_type FROM tbl_nonMember INNER JOIN tbl_customer ON tbl_nonMember.customerID = tbl_customer.customerID", con);
adap.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
tbMemship.Text = "";
tbPerses.Text = "";
tbDisc.Text = "";
ID = 0;
}
private void AdminForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tbl_customer' table. You can move, or remove it, as needed.
this.tbl_customerTableAdapter.Fill(this.database1DataSet.tbl_customer);
// TODO: This line of code loads data into the 'database1DataSet.tbl_nonMember' table. You can move, or remove it, as needed.
this.tbl_nonMemberTableAdapter.Fill(this.database1DataSet.tbl_nonMember);
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.tbl_customerTableAdapter.FillBy(this.database1DataSet.tbl_customer);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
//----------------------------------BUTTONS FOR PAY RATE-------------------------------------------------------------//
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView4_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
tbMemship.Text = dataGridView4.Rows[e.RowIndex].Cells[0].Value.ToString();
tbPerses.Text = dataGridView4.Rows[e.RowIndex].Cells[1].Value.ToString();
tbDisc.Text = dataGridView4.Rows[e.RowIndex].Cells[2].Value.ToString();
}
private void btn_update_Click(object sender, EventArgs e)
{
if (tbMemship.Text != "" && tbPerses.Text != "" && tbDisc.Text != "")
{
cmd = new SqlCommand("update tbl_payrates set Membership=#Membership,PerSession=#PerSession where Discounted=#Discounted", con);
con.Open();
cmd.Parameters.AddWithValue("#Membership", tbMemship.Text);
cmd.Parameters.AddWithValue("#PerSession", tbPerses.Text);
cmd.Parameters.AddWithValue("#Discounted", tbDisc.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
PayratesDisplay();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
private void btn_PRadd_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\Visual Studio 2010\Projects\RFG Inventory and Management System\RFG Inventory and Management System\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
cmd = new SqlCommand("INSERT INTO tbl_payrates (Membership, PerSession, Discounted) VALUES (#Membership, #PerSession, #Discounted)", con);
cmd.Parameters.AddWithValue("#Membership", tbMemship.Text);
cmd.Parameters.AddWithValue("#PerSession", tbPerses.Text);
cmd.Parameters.AddWithValue("#Discounted", tbDisc.Text);
cmd.ExecuteNonQuery();
}
}
private void btn_PRdel_Click_1(object sender, EventArgs e)
{
//Update button update dataset after insertion,upadtion or deletion
DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
if (ID != 0)
{
cmd = new SqlCommand("DELETE FROM tbl_payrates WHERE ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
PayratesDisplay();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
}
}
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. InventoryDb)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=InventoryDb;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
i think you are not assigned the value to id .so id always 0 and you are not able to delete the record. try to assign the value to ID and delete.i hope it will work without any problem.
private void btn_PRdel_Click_1(object sender, EventArgs e)
{
//Update button update dataset after insertion,upadtion or deletion
DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
if (ID != 0)// where is the id value?
{
cmd = new SqlCommand("DELETE FROM tbl_payrates WHERE ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
PayratesDisplay();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
I need to add value to table sales(acnum,scriptname,shares_bought) from transac(acnum,scriptname,Quantity,Price) using c# in visual studio 2008. I am using the code shown below, but it is not inserting value into sales database.
It is not showing any error or exception but its not updating sales table also.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
Con.Open();
string insertsale = "INSERT INTO sales(acnum, scriptname, shares_bought) select acnum,scriptname,Quantity from transac";
SqlCommand cmd = new SqlCommand(insertsale, Con);
cmd.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
The problem was that I had used PostUrl for the button click . . so i think it was redirecting to the nextpage without processing the code. Now its fixed .