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();
}
}
Related
I have a program that uses a dataGridView on Form1 to display data from a SQL Server database.
The user can also edit and save data back to the DB from the Form1 dataGridView.
However, I also have a search function that will pop up a new form and display the results of the search.
I want users to be able to save directly from the new window but at the moment it is only updating the data in the Form1 dataGridView.
This is what I am using to display the results of the Search.
private void ResultsFunc()
{
var ColumnToSearch = comboBox1.Text;
if (textBox1.Text.Length == 0)
{
var toSearchBy = listBox1.SelectedItem.ToString();
aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.DefaultView.RowFilter = ColumnToSearch + " = " + "'" + toSearchBy + "'";
}
else if (textBox1.Text.Length > 0)
{
var toSearchBy = textBox1.Text;
aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.DefaultView.RowFilter = ColumnToSearch + " = " + "'" + toSearchBy + "'";
}
Form2 resultsForm = new Form2();
resultsForm.dataGridView2.DataSource = aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.DefaultView;
resultsForm.Show();
}
This is what I am using to try save the data from Form2:
private void button1_Click(object sender, EventArgs e)
{
aSH_PROD_ORDERSTableAdapter.Update(aSH_ORDER_DBDataSet1);
}
How can I get the info entered in Form2 to save directly to the database rather than just update the dataGridView in Form1?
Have you tried SqlBulkCopy, it can update data to SQLServer
but make sure you have the necessary columns and schema in the datatable
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["SchoolConnectionString"].ConnectionString;
using (SqlConnection sqlConn = new SqlConnection(cs))
{
DataSet ds = aSH_ORDER_DBDataSet1;
DataTable dtStudentMaster = ds.Tables["Student"];
// ds.Tables["Student"], if aSH_ORDER_DBDataSet1 has multiple tables in it specify the table name else ds.Tables[0] is fine
sqlConn.Open();
using (SqlBulkCopy sqlbc = new SqlBulkCopy(sqlConn))
{
sqlbc.DestinationTableName = "StudentMaster";
// StudentMaster - Table need to be updated in SQLServer
// Make sure you have the similar column names and datatype in both datatable and sql server table
sqlbc.ColumnMappings.Add("Name", "Name");
sqlbc.ColumnMappings.Add("Phone", "Phone");
sqlbc.ColumnMappings.Add("Address", "Address");
sqlbc.ColumnMappings.Add("Class", "Class");
sqlbc.WriteToServer(dtStudentMaster);
Response.Write("Bulk data stored successfully");
}
}
}
catch (Exception ex)
{
throw ex;
}
}
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 am working one portal where user can login and will enter his details and later he can view those details after login again. But unfortunately data is not not displaying in page. Here is I am giving everything which I did.
Code Explanation:
This is the Button code for data in database.
protected void btnContactInfoSave_click(object sender, EventArgs e)
{
if (chkContactUpdate.Checked)
{
string[] ContactInfoData = new string[6];
ContactInfoData[0] = GlobalVars.UserEmail;
ContactInfoData[1] = txtCnct.Text;
ContactInfoData[2] = txtAltCnct.Text;
ContactInfoData[3] = txtEmrCnct.Text;
ContactInfoData[4] = txtPrsnEmail.Text;
ContactInfoData[5] = txtOfsEmail.Text;
Utilities.sqlUploadContactInfoData(ContactInfoData);
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Please click on the checkbox before Saving.');", true);
}
}
Here is the code for the Button creation :
When user clicks this button data should be added in database. wat ever the data user enters it has to save in database.
Code for uploading the data in database.
public static void sqlUploadContactInfoData(string[] Userdata) // code for saving the data in database
{
using (SqlConnection sqlConn = PortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "sp_testSample";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#CnctNum", Userdata[1].ToString());
cmd.Parameters.AddWithValue("#AltCnctNum", Userdata[2].ToString());
cmd.Parameters.AddWithValue("#EmerCnctNum", Userdata[3].ToString());
cmd.Parameters.AddWithValue("#PrsnEmail", Userdata[4].ToString());
cmd.Parameters.AddWithValue("#OfsEmail", Userdata[5].ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
Here I have a problem that I am unable to display the data in page.
When user clicks the button, data is saving in database. The problem is when user login and fill the data and he can save the data. once he logged out from portal and after login again data is not displaying there. Data need to save in page also.
Any problem in above code..??
string strCnctNum = txtCnctNum.Text;
//Then reset your control like below
`txtCnctNum.Text = "";
txtAltCnctNum.Text = "";
...
etc
// Then Use This Code to To Retrieve & Display Data
using (SqlConnection oSqlConnection = new SqlConnection("YourConnectionString"))
{
string strCommand = "Select * from YourTableName where CnctNum="+ strCnctNum +";
SqlCommand oCmd = new SqlCommand(strCommand, oSqlConnection);
oSqlConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
txtCnctNum.Text = oReader["CnctNum"].ToString();
txtAltCnctNum.Text = oReader["AltCnct"].ToString();
.....
etc
}
oSqlConnection.Close();
}
}`
I have a button that sends a session variable and redirects to another page where the page should read the variable and display data based off of the string of the session variable, and it works but it wont show unless I refresh the page. Heres the button click:
protected void btnJoin_Click(object sender, EventArgs e)
{
Button lb = (Button)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
getText1 = row.Cells[1].Text;
Session["showName"] = getText1;
Response.Redirect("ViewLeague.aspx");
}
and heres the page load for the ViewLeage.aspx:
string SQLName = "SELECT teamname, draftedPlayer1, player1FP, draftedPlayer2, player2FP, draftedPlayer3, player3FP, draftedPlayer4, player4FP, totalFP FROM Drafted_Table WHERE LeagueName = '" + Name2 + " '";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.Session["showName"] != null)
{
Name2 = (String)this.Session["showName"];
}
}
EDIT:
Heres where the data gets added to the gridview
private void GetData()
{
DataTable table = new DataTable();
// get the connection
using (SqlConnection conn = new SqlConnection("Data Source= tyler-pc\\sqlexpress; Integrated Security=true; Database=CODFANTASY2"))
{
// write the sql statement to execute
string sql = SQLName;
// instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
// fire Fill method to fetch the data and fill into DataTable
ad.Fill(table);
}
}
}
// specify the data source for the GridView
ViewLeagueTable.DataSource = table;
// bind the data now
ViewLeagueTable.DataBind();
}
any help is appreciated!
Two problems I'm seeing here...
First, when you perform a redirect:
Response.Redirect("ViewLeague.aspx");
The only events on the target page (ViewLeague.aspx) which will be invoked are the init/load/etc. events. A button click may have led to the redirect, but no button on the target page was clicked so no other such handler is going to be used.
Thus, in order for anything to show in the grid when that page loads, it needs to happen in the Page_Load handler:
protected void Page_Load(object sender, EventArgs e)
{
//...
GetData();
}
Second, you're using the value before you assign anything to it:
string SQLName = "SELECT teamname, draftedPlayer1, player1FP, draftedPlayer2, player2FP, draftedPlayer3, player3FP, draftedPlayer4, player4FP, totalFP FROM Drafted_Table WHERE LeagueName = '" + Name2 + " '";
// Later...
Name2 = (String)this.Session["showName"];
If Name2 was empty when you used it, then that SQL clause will be:
WHERE LeagueName = ''
So if there are no records with an empty LeagueName value, then there will be no data to show. You need to set the value in the query after you obtain the value. (And you should do so with a parameter, to avoid SQL injection.)
string SQLName = "SELECT teamname, draftedPlayer1, player1FP, draftedPlayer2, player2FP, draftedPlayer3, player3FP, draftedPlayer4, player4FP, totalFP FROM Drafted_Table WHERE LeagueName = #Name";
// Later...
Name2 = (String)this.Session["showName"];
// Later...
var cmd = new SqlCommand(SQLName);
cmd.Parameters.Add("#Name", SqlDataType.VarChar, 25).Value = Name2;
// etc.
(I had to guess on the column type and size, adjust accordingly.)
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.