Error in registration form code - c#

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

Related

SQL - Failed to convert string to Int32

try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] pram = new SqlParameter[7];
pram[0] = new SqlParameter("#fname", SqlDbType.VarChar, 50);
pram[1] = new SqlParameter("#lname", SqlDbType.VarChar, 50);
pram[2] = new SqlParameter("#dob", SqlDbType.VarChar, 50);
pram[3] = new SqlParameter("#gender", SqlDbType.Char, 10);
pram[4] = new SqlParameter("#fathername", SqlDbType.VarChar, 50);
pram[5] = new SqlParameter("#contact", SqlDbType.Int, 100);
pram[6] = new SqlParameter("#address", SqlDbType.VarChar, 50);
pram[0].Value = fname;
pram[1].Value = lname;
pram[2].Value = dob;
pram[3].Value = gender;
pram[4].Value = fathername;
pram[5].Value = contact;
pram[6].Value = address;
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
{
conn.Close();
}
Error received:
Failed to convert parameter value from a String to a Int32
You are probably passing a value that can't be parsed into an int for this parameter:
pram[5] = new SqlParameter("#contact", SqlDbType.Int, 100);
Check what you are passing here:
pram[5].Value = contact;
If contact is a string then do something like:
int contactNumber;
pram[5].Value = int.TryParse(contact, out contactNumber) ? contactNumber : 0;

remote database not updating after entering fields

I had made a registration page of the following code & when ever i run the code for enter data i am getting no errors , but when i refresh my remote database the field/information is not updated, I don't know where i am making mistake...
Here i am calling out my connection string from my web.config file.
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["RN_DBConnectionString"].ConnectionString;
}
below is the code, i am getting no errors in it but my remote database is been not updated. Iam doing something wrong..????
private void ExecuteInsert(string FName, string LName, string EID, string Password, string RPassword,
string Organization, string WPhone, string CPhone, string Country,
string City, string State, string Address)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO RN_DB.dbo.Table (FName, LName, EID, Password, RPassword, Organization, WPhone,CPhone,Country, City, State, Address) VALUES "
+ " (#FName,#LName,#EID,#Password,#RPassword,#Organization,#WPhone,#CPhone,#Country,#City,#State,#Addess)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[12];
//param[0] = new SqlParameter("#id", SqlDbType.NVarChar, 50);
param[0] = new SqlParameter("#FName", SqlDbType.NVarChar, 50);
param[1] = new SqlParameter("#LName", SqlDbType.NVarChar, 50);
param[2] = new SqlParameter("#EID", SqlDbType.NVarChar, 50);
param[3] = new SqlParameter("#Password", SqlDbType.NVarChar, 50);
param[4] = new SqlParameter("#RPassword", SqlDbType.NVarChar, 50);
param[5] = new SqlParameter("#Organization", SqlDbType.NVarChar, 50);
param[6] = new SqlParameter("#WPhone", SqlDbType.NVarChar, 50);
param[7] = new SqlParameter("#CPhone", SqlDbType.NVarChar, 50);
param[8] = new SqlParameter("#Country", SqlDbType.NVarChar, 50);
param[9] = new SqlParameter("#City", SqlDbType.NVarChar, 50);
param[10] = new SqlParameter("#State", SqlDbType.NVarChar, 50);
param[11] = new SqlParameter("#Address", SqlDbType.Text);
param[0].Value = FName;
param[1].Value = LName;
param[2].Value = EID;
param[3].Value = Password;
param[4].Value = RPassword;
param[5].Value = Organization;
param[6].Value = WPhone;
param[7].Value = CPhone;
param[8].Value = City;
param[9].Value = Country;
param[10].Value = State;
param[11].Value = Address;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Pass.Text == RPass.Text)
{
Guid newGUID = Guid.NewGuid();
//call the method to execute insert to the database
ExecuteInsert(FName.Text,
LName.Text,
EID.Text, Pass.Text, RPass.Text, Org.Text, WPhone.Text, CPhone.Text,
Country.Text,
City.Text, State.Text, Address.Text);
Response.Write("Record was successfully added!");
}
else
{
Response.Write("Password's didnot match");
Pass.Focus();
}
You probably have an error message, but you lose it here:
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
Your msg local variable gets the message you need, but you do not show it anywhere. You need to do something: either show it somewhere or throw the exception further.

How to update information into database wpf

I want to use the following code to update when a button is clicked. But I want to update the additionalInformation only. How would I go about doing this?
public static void Update(Resident resident, SqlConnection connection, SqlTransaction transaction)
{
StringBuilder sqlString = new StringBuilder();
SqlCommand command;
sqlString.Append("UPDATE [Resident] SET ");
sqlString.Append("title = #title, ");
sqlString.Append("firstName = #firstName, ");
sqlString.Append("surname = #surname, ");
sqlString.Append("dateOfBirth = #dateOfBirth, ");
sqlString.Append("photo = #photo, ");
sqlString.Append("doctorID = #doctorID, ");
sqlString.Append("roomID = #roomID, ");
sqlString.Append("allergies = #allergies, ");
sqlString.Append("additionalInformation = #additionalInformation ");
sqlString.Append("WHERE residentID = #residentID ");
command = new SqlCommand(sqlString.ToString(), connection);
if ((transaction != null)) command.Transaction = transaction;
command.Parameters.Add("#residentID", SqlDbType.Int).Value = resident.ResidentID;
command.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = Helper.GetValue(resident.Title);
command.Parameters.Add("#firstName", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.FirstName);
command.Parameters.Add("#surname", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.Surname);
command.Parameters.Add("#dateOfBirth", SqlDbType.DateTime).Value = Helper.GetValue(resident.DateOfBirth);
command.Parameters.Add("#photo", SqlDbType.Image, 2147483647).Value = Helper.GetValue(resident.Photo);
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
command.Parameters.Add("#roomID", SqlDbType.Int).Value = resident.Room.RoomID;
command.Parameters.Add("#allergies", SqlDbType.NText).Value = resident.Allergies;
command.Parameters.Add("#additionalInformation", SqlDbType.NText).Value = resident.addtionalInformation;
int rowsAffected = command.ExecuteNonQuery();
if (!(rowsAffected == 1))
{
throw new Exception("An error has occurred while updating Resident details.");
}
}
You can pass one more parameter indicating that you want to update only addidionalInformation, for example:
public static void Update(Resident resident, SqlConnection connection, SqlTransaction transaction, bool updateOnlyAdditionalInformation)
{
StringBuilder sqlString = new StringBuilder();
SqlCommand command;
sqlString.Append("UPDATE [Resident] SET ");
if (!updateOnlyAdditionalInformation)
{
sqlString.Append("title = #title, ");
sqlString.Append("firstName = #firstName, ");
sqlString.Append("surname = #surname, ");
sqlString.Append("dateOfBirth = #dateOfBirth, ");
sqlString.Append("photo = #photo, ");
sqlString.Append("doctorID = #doctorID, ");
sqlString.Append("roomID = #roomID, ");
sqlString.Append("allergies = #allergies, ");
}
sqlString.Append("additionalInformation = #additionalInformation ");
sqlString.Append("WHERE residentID = #residentID ");
command = new SqlCommand(sqlString.ToString(), connection);
if ((transaction != null)) command.Transaction = transaction;
command.Parameters.Add("#residentID", SqlDbType.Int).Value = resident.ResidentID;
command.Parameters.Add("#additionalInformation", SqlDbType.NText).Value = resident.addtionalInformation;
if (!updateOnlyAdditionalInformation)
{
command.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = Helper.GetValue(resident.Title);
command.Parameters.Add("#firstName", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.FirstName);
command.Parameters.Add("#surname", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.Surname);
command.Parameters.Add("#dateOfBirth", SqlDbType.DateTime).Value = Helper.GetValue(resident.DateOfBirth);
command.Parameters.Add("#photo", SqlDbType.Image, 2147483647).Value = Helper.GetValue(resident.Photo);
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
command.Parameters.Add("#roomID", SqlDbType.Int).Value = resident.Room.RoomID;
command.Parameters.Add("#allergies", SqlDbType.NText).Value = resident.Allergies;
}
int rowsAffected = command.ExecuteNonQuery();
if (!(rowsAffected == 1))
{
throw new Exception("An error has occurred while updating Resident details.");
}
}

ASP.NET C# Missing Expression Error during Oracle insert

May I start off by saying this is my 1st assigned database project in 10 years... and 1st time doing it in C#. I am "simply" trying to insert form data into an Oracle table using OleDB.
I keep getting "ORA-00936: missing expression". Below is my code... any idea what's missing?
public string getConnString()
{
//set the connection string from web config file
return WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
private void executeInsert(string EventType, string EventSubType, string DeptName, string EventDate, string Duration, string EventName, string EventAdd, string WardNo, string Program, string NumAtt, string StTime, string EndTime, string MngName, string RecKeeper)
{
OleDbConnection conn = new OleDbConnection(getConnString());
string sql = "INSERT INTO APPS.CLV_EVENT_TRACK (EVENTTYPE, EVENTSUBTYPE, DEPTNAME, EVENTDATE, DURATION, EVENTNAME, EVENTADD, WARDNO, PROGRAM, NUMATT, STARTTIME, ENDTIME, MNGNAME, RECORDKEEPER) VALUES "
+ "(#EventType, #EventSubType, #DeptName, TO_DATE(#EventDate, 'Month dd, YYYY'), #Duration, #EventName, #EventAdd, #WardNo, #Program, #NumAtt, TO_DATE(#StTime, 'HH:MI:SS PM'), TO_DATE(#EndTime, 'HH:MI:SS PM'), #MngName, #RecKeeper)";
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbParameter[] param = new OleDbParameter[14];
param[0] = new OleDbParameter("#EventType", OleDbType.VarChar, 25);
param[1] = new OleDbParameter("#EventSubType", OleDbType.VarChar, 80);
param[2] = new OleDbParameter("#DeptName", OleDbType.VarChar, 240);
param[3] = new OleDbParameter("#EventDate", OleDbType.Date);
param[4] = new OleDbParameter("#Duration", OleDbType.Numeric);
param[5] = new OleDbParameter("#EventName", OleDbType.VarChar, 80);
param[6] = new OleDbParameter("#EventAdd", OleDbType.VarChar, 150);
param[7] = new OleDbParameter("#WardNo", OleDbType.VarChar, 25);
param[8] = new OleDbParameter("#Program", OleDbType.VarChar, 150);
param[9] = new OleDbParameter("#NumAtt", OleDbType.Numeric);
param[10] = new OleDbParameter("#StTime", OleDbType.Date);
param[11] = new OleDbParameter("#EndTime", OleDbType.Date);
param[12] = new OleDbParameter("#MngName", OleDbType.VarChar, 150);
param[13] = new OleDbParameter("#RecKeeper", OleDbType.VarChar, 150);
param[0].Value = EventType;
param[1].Value = EventSubType;
param[2].Value = DeptName;
param[3].Value = EventDate;
param[4].Value = Duration;
param[5].Value = EventName;
param[6].Value = EventAdd;
param[7].Value = WardNo;
param[8].Value = Program;
param[9].Value = NumAtt;
param[10].Value = StTime;
param[11].Value = EndTime;
param[12].Value = MngName;
param[13].Value = RecKeeper;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex) { throw ex; }
finally
{
conn.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var start = DateTime.Parse(txtStTime.Text);
var end = DateTime.Parse(txtEndTime.Text);
TimeSpan duration = end.Subtract(start);
string meetDuration = duration.TotalMinutes.ToString();
executeInsert(rbEventType.SelectedItem.Text, ddVolType.SelectedItem.Text,
txtDept.Text, txtEventDate.Text, meetDuration, txtEventName.Text,
txtEventAdd.Text, ddWard.SelectedItem.Value, txtSBPlan.Text, txtNumVol.Text,
txtStTime.Text, txtEndTime.Text, txtEventMgr.Text, txtRecording.Text);
}
UPDATE to code:
public string getConnString()
{
//set the connection string from web config file
return WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
private void executeInsert(string EventType, string EventSubType, string DeptName, string EventDate, string Duration, string EventName, string EventAdd, string WardNo, string Program, string NumAtt, string StTime, string EndTime, string MngName, string RecKeeper)
{
OleDbConnection conn = new OleDbConnection(getConnString());
string sql = "INSERT INTO APPS.CLV_EVENT_TRACK (EVENTTYPE, EVENTSUBTYPE, DEPTNAME, EVENTDATE, DURATION, EVENTNAME, EVENTADD, WARDNO, PROGRAM, NUMATT, STARTTIME, ENDTIME, MNGNAME, RECORDKEEPER) VALUES "
+ "(#EventType, #EventSubType, #DeptName, TO_DATE(#EventDate, 'Month dd, YYYY'), #Duration, #EventName, #EventAdd, #WardNo, #Program, #NumAtt, TO_DATE(#StTime, 'HH:MI:SS PM'), TO_DATE(#EndTime, 'HH:MI:SS PM'), #MngName, #RecKeeper)";
try
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#EventType", EventType),
new OleDbParameter("#EventSubType", EventSubType),
new OleDbParameter("#DeptName", DeptName),
new OleDbParameter("#EventDate", EventDate),
new OleDbParameter("#Duration", Duration),
new OleDbParameter("#EventName", EventName),
new OleDbParameter("#EventAdd", EventAdd),
new OleDbParameter("#WardNo", WardNo),
new OleDbParameter("#Program", Program),
new OleDbParameter("#NumAtt", NumAtt),
new OleDbParameter("#StTime", StTime),
new OleDbParameter("#EndTime", EndTime),
new OleDbParameter("#MngName", MngName),
new OleDbParameter("#RecKeeper", RecKeeper)
});
cmd.ExecuteNonQuery();
}
}
catch (Exception ex) { throw ex; }
finally
{
conn.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var start = DateTime.Parse(txtStTime.Text);
var end = DateTime.Parse(txtEndTime.Text);
TimeSpan duration = end.Subtract(start);
string meetDuration = duration.TotalMinutes.ToString();
executeInsert(rbEventType.SelectedItem.Text, ddVolType.SelectedItem.Text,
txtDept.Text, txtEventDate.Text, meetDuration, txtEventName.Text,
txtEventAdd.Text, ddWard.SelectedItem.Value, txtSBPlan.Text, txtNumVol.Text,
txtStTime.Text, txtEndTime.Text, txtEventMgr.Text, txtRecording.Text);
}
What a lesson to learn. Apparently an ORACLE parameter has to be presented as a "?"
So, my final code... that actually successfully inserts a record is:
public string getConnString()
{
//set the connection string from web config file
return WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
private void executeInsert()
{
OleDbConnection conn = new OleDbConnection(getConnString());
string sql = "INSERT INTO APPS.CLV_EVENT_TRACK (EVENTTYPE, EVENTSUBTYPE, DEPTNAME, EVENTDATE, DURATION, EVENTNAME, EVENTADD, WARDNO, PROGRAM, NUMATT, STARTTIME, ENDTIME, MNGNAME, RECORDKEEPER) ";
sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try
{
var start = DateTime.Parse(txtStTime.Text);
var end = DateTime.Parse(txtEndTime.Text);
TimeSpan duration = end.Subtract(start);
string meetDuration = duration.TotalMinutes.ToString();
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = rbEventType.SelectedItem.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ddVolType.SelectedItem.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtDept.Text;
cmd.Parameters.Add("?", OleDbType.Date).Value = txtEventDate.Text;
cmd.Parameters.Add("?", OleDbType.Numeric).Value = meetDuration;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtEventName.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtEventAdd.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ddWard.SelectedItem.Value;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtSBPlan.Text;
cmd.Parameters.Add("?", OleDbType.Numeric).Value = txtNumVol.Text;
cmd.Parameters.Add("?", OleDbType.Date).Value = txtStTime.Text;
cmd.Parameters.Add("?", OleDbType.Date).Value = txtEndTime.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtEventMgr.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtRecording.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex) { throw ex; }
finally
{
conn.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
executeInsert();
}

Picture appear blurred after the select statement

//-------------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

Categories

Resources