Picture appear blurred after the select statement - c#

//-------------SELECT STATEMENT---------
private void comboBoxLogin_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxLogin.SelectedIndex.ToString() != string.Empty)
splitContainer1.Panel2.Enabled = true;
if (comboBoxLogin.SelectedItem.ToString() == "Create New User")
groupBoxNewUser.Visible = true;
else groupBoxNewUser.Visible = false;
if(comboBoxLogin.SelectedItem.ToString()!="Create New User"){
string DBConnection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Timesheet.mdf;Integrated Security=True;User Instance=True";
sqlConnection = new SqlConnection(DBConnection);
try {
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.CommandText = "SELECT firstname, lastname, NDFuserID, picture FROM UserRegistration WHERE NDFuserID='" +comboBoxLogin.SelectedItem + "'";
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if(sqlDataReader.Read())
{
labelUserDetails.Text = sqlDataReader["firstname"].ToString() + " " + sqlDataReader["lastname"].ToString();
byte[] pictureByteReader = (byte[])sqlDataReader["picture"];
MemoryStream ms = new MemoryStream(pictureByteReader);
Image picture = Image.FromStream(ms);
pictureBoxUserDetails.Image = picture;
}
comboBoxItems.Refresh();
}
catch(Exception ex){
MessageBox.Show(ex.ToString());
}
finally{
sqlConnection.Close();
}
}
}
//--------------------INSERT STATEMENT-------------------------
private void btnCreateNewUser_Click(object sender, EventArgs e)
{
string DBConnection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Timesheet.mdf;Integrated Security=True;User Instance=True";
sqlConnection = new SqlConnection(DBConnection);
try
{
//--Insert statement for a picture-----------------------
FileInfo fileImage = new FileInfo(txtPictureURL.Text);
var fileLength = fileImage.Length;
byte[] picutreByte = new byte[Convert.ToInt32(fileLength)];
FileStream fileStreams = new FileStream(txtPictureURL.Text, FileMode.Open, FileAccess.Read, FileShare.Read);
int readByte = fileStreams.Read(picutreByte, 0, Convert.ToInt32(fileLength));
fileStreams.Close();
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.CommandText = "INSERT INTO UserRegistration(firstname, lastname, NDFuserID, phone, picture) VALUES(#firstname, #lastname, #NDFuserID, #phone, #picture)";
sqlCommand.Parameters.Add("#firstname", SqlDbType.NVarChar, 50);
sqlCommand.Parameters.Add("#lastname", SqlDbType.NVarChar, 50);
sqlCommand.Parameters.Add("#NDFuserID", SqlDbType.NChar, 10);
sqlCommand.Parameters.Add("#phone", SqlDbType.NVarChar);
sqlCommand.Parameters.Add("#picture", SqlDbType.Image);
sqlCommand.Parameters["#firstname"].Value = txtFirstName.Text;
sqlCommand.Parameters["#lastname"].Value = txtLastname.Text;
sqlCommand.Parameters["#NDFuserID"].Value = "NDF-" +txtUserID.Text;
sqlCommand.Parameters["#phone"].Value = maskedtxtPhone.Text;
sqlCommand.Parameters["#picture"].Value = picutreByte;
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sqlConnection.Close();
txtFirstName.Text = "";
txtLastname.Text = "";
txtPictureURL.Text = "";
txtUserID.Text = "";
maskedtxtPhone.Text = "";
}
}
I do not know which of this has a problem. either the insert statement or the select statement. When i insert it does not give any exception but when I try to select it show an exception and the picture appears blurred in the picturebox. What have i done wrong? Please help.Thanks.

While there are easier ways to accomplish some of your steps such as
byte[] PictureBytes = File.ReadAllBytes(txtPictureURL.Text);
Also the comment from #Khan should be heeded.
Neither of your methods appear to be causing any degradation in the copied.
I suspect the PictureBox properties might be scaling or stretching the image.
To fix that issue change the PictureBox.SizeMode property to AutoSize.
If the image is larger than the PictureBox, then you can implement scrollbars like this answer: https://stackoverflow.com/a/4710193/2549384

Related

SQL commands not working in C# (ASP.NET web forms)

I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}

"Parameter is not valid" error when retrieving image

I want to retrieve images from a SQL Server database using C#. However, I'm getting the error message
Parameter is not valid
Please help me.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string q = "select * from Rough where name='" + comboBox1.Text + "'";
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=SMS_DB;Integrated Security=True");
SqlCommand cmd = new SqlCommand(q, con);
SqlDataReader dr;
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
byte[] img = null;
while (dr.Read())
{
textBox1.Text = (dr["ID"].ToString());
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Image"].ToString());
img = (byte[])(dr["Image"]);
if (img == null)
{
pictureBox2.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms);
// ms.Close();
}
}
con.Close();
}
}

Error in registration form code

I'm creating a registration form using using Visual Studio 2015, but when I run my code some problem occurs. I receive the error as stated bellow:
I could not found the problem with my code:
private void execution(string RNumber, string fname, string lname, string Password, string Gender, string CPassword, string Email)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Table(RNumber, fname, lname, Password, Gender, CPassword, Email) VALUES "
+ " (#RNumber, #fname, #lname, #Password, #Gender, #CPassword, #Email)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] pram = new SqlParameter[7];
pram[0] = new SqlParameter("#RNumber", SqlDbType.VarChar, 50);
pram[1] = new SqlParameter("#fname", SqlDbType.VarChar, 50);
pram[2] = new SqlParameter("#lname", SqlDbType.VarChar, 50);
pram[3] = new SqlParameter("#Password", SqlDbType.VarChar, 50);
pram[4] = new SqlParameter("#Gender", SqlDbType.VarChar, 50);
pram[5] = new SqlParameter("#CPassword", SqlDbType.VarChar, 50);
pram[6] = new SqlParameter("#Email", SqlDbType.VarChar, 50);
pram[0].Value = RNumber;
pram[1].Value = fname;
pram[2].Value = lname;
pram[3].Value = Password;
pram[4].Value = Gender;
pram[5].Value = CPassword;
pram[6].Value = Email;
for (int i = 0; i < pram.Length; i++)
{
cmd.Parameters.Add(pram[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex_msg)
{
string msg = "Error occured while inserting";
msg += ex_msg.Message;
throw new Exception(msg);
}
finally
{
//Here will be fially elements
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
protected void Buttonsubmit_Click(object sender, EventArgs e)
{
if (TextBoxregstr.Text == "")
{
Response.Write("Please complete the form.");
}
else
{
execution(TextBoxregstr.Text, TextBoxfirst.Text, TextBoxlast.Text, TextBoxpswrd.Text, TextBoxcnfrmpswrd.Text, TextBoxgender.Text, TextBoxemail.Text);
Confirm.Visible = true;
TextBoxfirst.Text = "";
TextBoxlast.Text = "";
TextBoxpswrd.Text = "";
TextBoxgender.Text = "";
TextBoxcnfrmpswrd.Text = "";
TextBoxemail.Text = "";
TextBoxregstr.Text = "";
}
}
As the error indicates,
Incorrect syntax near the keyword 'Table'
It happens because TABLE is a reserved keyword for T-SQL. your query should enclose TABLE in square brackets
string sql = "INSERT INTO [Table]
Better way to handle is you change the name and use a more descriptive word for the table

datatable won't update

I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}

Updating records

private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True"))
{
string sqlQuery = #"UPDATE cottonpurchase SET #slipNo, #basicprice, #weight, #totalamountbasic, #premium, #totalamountpremium, #totalamountpaid, #yeildestimates WHERE farmercode = #farmercode";
{
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
cmd.Parameters.Add("#slipNo", SqlDbType.Int).Value = TxtSlipNo.Text;
cmd.Parameters.Add("#basicprice", SqlDbType.Int).Value = TxtBasicPrice.Text;
cmd.Parameters.Add("#weight", SqlDbType.Int).Value = TxtWeight.Text;
cmd.Parameters.Add("#totalamountbasic", SqlDbType.Int).Value = TxtTotalAmountBasic.Text;
cmd.Parameters.Add("#premium", SqlDbType.Int).Value = TxtPremium.Text;
cmd.Parameters.Add("#totalamountpremium", SqlDbType.Int).Value = TxtTotalAmountPremium.Text;
cmd.Parameters.Add("#totalamountpaid", SqlDbType.Int).Value = TxtTotalAmountPaid.Text;
cmd.Parameters.Add("#yeildestimates", SqlDbType.Int).Value = TxtYeildEstimates.Text;
sqlConn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
It's giving me an error even though everything seems fine with my code:
error : incorrect syntax near ','
You need to specify column names that you are trying to set.
string sqlQuery = #"
UPDATE cottonpurchase
SET
slipNo = #slipNo,
basicprice= #basicprice,
weight = #weight,
totalamountbasic = #totalamountbasic,
premium = #premium,
totalamountpremium = #totalamountpremium,
totalamountpaid = #totalamountpaid,
yeildestimates = #yeildestimates
WHERE farmercode = #farmercode";
Also, you didn't provide #farmercode parameter:
cmd.Parameters.AddWithValue("#farmercode", <someValue>);
You forgot to mention the column names in the set.
string sqlQuery = #"UPDATE cottonpurchase SET slipNo=#slipNo, basicprice=#basicprice, ... WHERE farmercode = #farmercode";

Categories

Resources