Here i have write the coding for image upload control.but getting some RUNTIME error.error sows in SqlConnection place
first i have
1.Image name box - Textbox
2.Image Upload control - asp imageupload control
3.Upload button
ERROR :Object synchronization method was called from an unsynchronized block of code.
Code Below
public partial class ProfileDetails : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
//SqlConnection con = new SqlConnection("Data Source=CHATHU-LAPTOP;Initial Catalog=ProfilemgtDB;User ID=sa;Password=sa123");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void Upload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("images/");
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName);
if (ext == ".jpg" || ext == ".png")
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
string name = "~/images/" + FileUpload1.FileName;
string s = "Insert into Profile values('" + TextBox12.Text.Trim() + " '.'" + name + "' )";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("File Uploaded");
}
else
{
Response.Write("You can upload only JPG & PNG");
}
}
else {
Response.Write("Please Select File");
}
}
}
ERROR :Object synchronization method was called from an unsynchronized block of code.
Nimesh,
I do not see anything wrong in the code. However, you may want to check if your web.config contains the same connectionStrings name as mentioned in your code (which is ConnectionString).
Also, refer the following links
http://www.ezzylearning.com/tutorial.aspx?tid=4287517
http://forums.asp.net/t/1757347.aspx/1
Hope this helps.
Related
I am new to C# and i am trying to insert some values to my database i created inside visual studio.
-I am creating a recipe application-
So in the form i have some components such as text boxes(For title,ingredients,description), a dropdown item(combobox) to specify if it's food or sweet and a button to insert all these data into my database.
When i am pressing the button i can add everything(all the text boxes) to the database except the dropdown value.
Here is the code inside the button_click
private void addItemButton_Click(object sender, EventArgs e)
{
string dat = "Insert into [Table](Title,Category,Ingredients,Description) Values('" + titleTextBox.Text + "','" + dropdownCategory.SelectedValue + "','" + addIngredientTextBox.Text + "','" + addDescriptionTextBox.Text + "')";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
I make a code example, which can insert the combobox value to the database successfully.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string dat = string.Format("Insert into [Sample](Title,Category,Ingredients,Description)values('{0}','{1}','{2}','{3}')", textBox1.Text, comboBox1.SelectedItem,textBox2.Text,textBox3.Text);
string connectionString = #"connectionstring";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("success");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.AddRange(new object[] { "basketball","football", "volleyball" });
}
}
I would try to look into content of string dat.
It might contain invalid data if "dropdownCategory.SelectedValue" returns something
that you don't expect.
Other than that, order of Open(), ExecuteNonQuery() and Close() methods might be incorrect. Try to read docs of these methods.
Another thing that you should look into is error message that is returned(if there is one). They are usually pretty informative.
Ok i don't know if it's correct or not but it worked on me.
I changed
dropdownCategory.SelectedValue
to
dropdownCategory.Text
and it worked.
I am trying to code an accounting system into which I should enter a product id, product name and product price. After that it should be stored in a .accdb file
My problem is when I enter more than 10 digits into product id the datagridview gives me an error saying that the value is too large for int32 type.
Error:
Additional information: Value was either too large or too small for an
Int32.Couldn't store <6221060003181> in Item_Code Column. Expected
type is Int32.
When I open the accdb file, I found the data stored; but next time I open the form, it gives me that error!
public partial class Productentry : MetroFramework.Forms.MetroForm
{
public OleDbConnection connection = new OleDbConnection();
public Productentry()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Sama_Software\WindowsFormsApplication1\WindowsFormsApplication1\DB.accdb;Jet OLEDB:Database Password=**************";
}
private void Productentry_Load(object sender, EventArgs e)
{
ViewData();
// TODO: This line of code loads data into the 'dBDataSet.Product' table. You can move, or remove it, as needed.
this.productTableAdapter1.Fill(this.dBDataSet.Product);
ViewData();
}
void ViewData()
{
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Product]",connection);
da.Fill(this.dBDataSet.Product);
}
private void bunifuButton4_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuButton3_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("INSERT INTO [Product] (Item_Code, Item_Name, Price) VALUES ('" + Pidn.Text + "','" + name.Text + "','" + price.Text + "')", connection);
da.Fill(dBDataSet)
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void Cat_TextChange(object sender, EventArgs e)
{
}
private void bunifuButton1_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("UPDATE [Product] WHERE [Item_Code]=" + Pidn.Text + " SET [Item_Name]='" + name.Text + "',[Price]=" + price.Text + "", connection);
da.Fill(dBDataSet);
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void bunifuButton4_Click_1(object sender, EventArgs e)
{
this.Close();
}
private void Pid_TextChange(object sender, EventArgs e)
{
}
}
}
Store the barcode as text.
Even though it is build by digits, it is not a number but a code of fixed length, and it may even have a leading zero.
I have to create a page an aspx page that allows me to modify the data of the listview row that are associated to a db, but I can't get the values.
I tried to do a query string
protected void EditButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(((Button)sender).Attributes["ID_Persona"]);
Response.Redirect("http://localhost:60082/pages/Edit.aspx" + "?
ID_Persona=" + id);
}
and to take the value on the page where I need it
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString.Get("ID_Persona").ToString();
}
but I don't know how to display the line I want to edit in the textboxes.
this is the button that redirects to the edit page
protected void EditButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(((Button)sender).Attributes["ID_Persona"]);
Response.Redirect("http://localhost:60082/pages/Edit.aspx" + "?
ID_Persona=" + id);
}
this is the edit page
public partial class Edit : System.Web.UI.Page
{
string constr =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString.Get("ID_Persona").ToString();
}
protected void CustomerUpdate(object sender, EventArgs e)
{
CustomerUpdate();
}
private int Id
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["ID"]) ? int.Parse(Request.QueryString["ID"]) : 0;
}
}
private void CustomerUpdate()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Persona SET Nome=#Nome, Cognome=#Cognome,Email=#Email,CodiceFiscale=#CodiceFiscale WHERE ID=#ID", con))
{
cmd.Parameters.AddWithValue("Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("Email", TextBox20.Text);
cmd.Parameters.AddWithValue("CodiceFiscale",TextBox22.Text);
cmd.Parameters.AddWithValue("ID", "");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri, false);
Response.Redirect("Dash.aspx");
}
}
}
}
I think that you shuld make public the methods which sends the information like the query but i'm not sure that will work.
I solved that
if (queryy == "1")
{
B2.Visible = false;
var connectionString =
ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM
Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID",
Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
TextBox1.Text = rdr["Nome"].ToString();
TextBox15.Text = rdr["Cognome"].ToString();
TextBox20.Text = rdr["Email"].ToString();
TextBox22.Text = rdr["CodiceFiscale"].ToString();
}
}
}
}
I am working in Visual Studio 2010 and I am trying to upload documents via a webpage to an access database. I am not getting any errors when I run my code, but nothing is writing to the database. Here is my on click code to show what I think it is supposed to do.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" || fileExtension.ToLower() != ".docx" || fileExtension.ToLower() != ".pdf")
{
lblInfo.Text = "Only .doc, .docx, or .pdf files are allowed.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize > 2097152)
{
lblInfo.Text = "Maximum file size of 2 MB exceeded.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
OleDbCommand update = new OleDbCommand("Update STAFF SET Resume = #Resume WHERE StaffID=#StaffID", DBConnection);
update.Parameters.Add("#Resume", OleDbType.LongVarBinary).Value = FileUpload1.FileContent;
update.Parameters.Add("#StaffID", OleDbType.Integer).Value = txtStaffID.Text;
lblInfo.Text = "File Uploaded";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
else
{
lblInfo.Text = "Please select a file to upload";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
}
If you could provide any advice or suggestions that would be great. Thanks. I will show the entirety of the code also, just in case it's an issue with the DB connection.
public partial class Staff : System.Web.UI.Page
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CIS470_TPS_System\CIS470_TPS_System\CIS470_TPS_System\App_Data\TpsSystem_DB.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From STAFF", DBConnection);
DataAdapter.Fill(LocalDataTable);
}
private void Page_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
protected void AccessDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string requestId = GridView1.SelectedRow.Cells[1].Text;
txtSelectedStaff.Text = requestId; //this control holds the selected value
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
}
As suggested in the comments to the question, we can use the FileUpload control's .FileBytes property to supply the value of the query parameter, as in this (simplified) example:
protected void btnUpload_Click(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\staffDb.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"UPDATE STAFF SET Resume=? " +
"WHERE StaffID=?";
cmd.Parameters.AddWithValue("?", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
con.Close();
}
}
I keep getting this error:
Format of the initialization string does not conform to specification starting at index 0.
This line of code:
using (OleDbConnection conn = new OleDbConnection("PayrollSystem_DBConnectionString"))
I think I need sql statements instead of Ole, I'm not sure.
Here is my form html code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>"
ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>"
Here is my frmManageUsers code:
public partial class frmManageUsers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAddUser_Click1(object sender, EventArgs e)
{
//string userName, userPassword;
if (txtUserName.Text == "" || txtUserName.Text == null)
{
lblError.Text = ("User Name may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
// else
// userName = (txtUserName.Text);
if (txtPassword.Text == "" || txtPassword.Text == null)
{
lblError.Text = ("Password may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
//else
// userPassword = (txtPassword.Text);
using (OleDbConnection conn = new OleDbConnection("PayrollSystem_DBConnectionString"))
{
string insert = "Insert INTO tblUserLogin (UserName, UserPassword, SecurityLevel) Values (#UserName, #UserPassword, #SecurityLevel)";
OleDbCommand cmd = new OleDbCommand(insert, conn);
cmd.Parameters.Add("#UserName", txtUserName.Text);
cmd.Parameters.Add("#UserPassword", txtPassword.Text);
cmd.Parameters.Add("#SecurityLevel", drpdwnlstSecurityLevel.SelectedValue);
cmd.ExecuteNonQuery();
}
Session["UserName"] = txtUserName.Text;
Session["Password"] = txtPassword.Text;
Session["SecurityLevel"] = drpdwnlstSecurityLevel.SelectedValue;
Server.Transfer("frmManageUsers.aspx");
//Server.Transfer("grdUserLogin");
}
protected void drpdwnlstSecurityLevel_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
OleDbConnection takes the actual connection string, not the NAME of the connection string. You have to get the connection string from the Configuration using ConfigurationManager.ConnectionStrings["PayrollSystem_DBConnectionString"].ConnectionString and pass that to OleDbConnection
Also, if you're using a 64-bit system, you need to change the connection string to use the new provider, Microsoft.ACE.OLEDB.14.0
You can download it here:
Microsoft.ACE.OLEDB.14.0 .NET Database Provider