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.");
}
}
Related
I have a database made up of 2 (more, actually, but only 2 im working with) tables.
The Material table consists solely of the material-number and the description
DPMatNr
DPBezeichnung
The Eigenschaften table is there to hold the properties of the materials.
It uses the columns:
EigenschaftenBezeichnerID
Wert (value)
My problem is: each entry in the Material table needs to have multiple entries in the Eigenschaften table.
For example:
"Material":
DPMatNr = 001,
DPBezeichnung = "Description"
"Eigenschaften":
EigenschaftenBezeichnerID = 1,
Wert = "A4"
EigenschaftenBezeichnerID = 3,
Wert = "80" and so on.
My code currently looks like this:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string query = #"Insert INTO dbo.Material (DPMatNr, DPBezeichnung)
VALUES (#matnummer, #bezeichnung)";
string query2 = #"Insert INTO dbo.Eigenschaften
(EigenschaftenBezeichnerID, Wert)
VALUES (#1, #format, #2, #grammatur, #3, #gewicht,
#4, #eform, #5, #kuvertierung,
#6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cn.Open();
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
Now I currently get an error that says:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Material' with unique index 'IX_MatNrUnique'
What am I doing wrong?
The Problem here is, that for every "Eigenschaft" you insert into the table you also try to create an entry in the "Material" table. But since every material should only be inserted once (therefore the primary key) you get the error.
Edit:
You could adjust your method like the following:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string check = "Select COUNT(*) FROM dbo.Material where DPMatNr = #matnummer";
string query = "Insert INTO dbo.Material (DPMatNr, DPBezeichnung)" + "VALUES (#matnummer, #bezeichnung)";
string query2 = "Insert INTO dbo.Eigenschaften (EigenschaftenBezeichnerID, Wert)" + "VALUES (#1, #format, #2, #grammatur, #3, #gewicht, #4, #eform, #5, #kuvertierung, #6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand chkCom = new SqlCommand(check, cn))
{
cn.Open();
chkCom.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
int? matCnt = chkCom.ExecuteScalar() as int?;
if (matCnt == 0 || matCnt == null)
{
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cmd.ExecuteNonQuery();
}
}
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
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
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;
I have a feature to upload the Excel sheet data into the gridview. The data will get inserted into the child table of database.
Now, My issue here is. One of the column has a relation with the Master table.
So, untill and unless I add that column ID which has a relation it gives me error as
The Student_id column was not supplied
Here is my code
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select count(email) from tbl_student_report where email=#email", con);
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = dt.Rows[i]["Email Id"].ToString();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Duplicate user in the sheet, Sheet will not be uploaded..!!!');window.location ='csrstudentprogress.aspx';", true);
continue;
}
cmd = new SqlCommand("INSERT INTO tbl_student_report(NgoId,student_id,name,email,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#NgoId,#student_id,#name,#email,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = dt.Rows[i]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = dt.Rows[i]["StudentId"].ToString();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
Please suggest what to do in this case, because User will not add student_id in the excel sheet and upload.
I am using sql-server 2008
How to achieve this ??
I got it done by trying myself like below:-
Helper class
public static DataTable GetUserIdByName(string userName,string userType)
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_User WHERE Username=#Username AND UserType=#UserType", con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("#UserType", SqlDbType.VarChar).Value = userType;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
}
And calling the Class in the Export function did the job:-
DataTable table = GeneralHelper.GetUserIdByName(Session["User"].ToString(), Session["UserType"].ToString());
for (int i = 0; i < dt.Rows.Count; i++)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
if (table != null && table.Rows.Count > 0)
{
string StudentId = GetNgoIdStudentId(dt.Rows[i]["Email Id"].ToString());
if (StudentId != null)
{
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_student_report(student_id,name,emailid,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#student_id,#name,#emailid,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = table.Rows[0]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = StudentId;
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#emailid", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
if (string.IsNullOrEmpty(dt.Rows[i]["Date Of Record"].ToString()))
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
}
if (string.IsNullOrEmpty(dt.Rows[i]["Modified Date"].ToString()))
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
}
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Student not found');", true);
}
}
else
{
//Error
}
}
}
I am trying to catch exception while updating a gridview.
code is
public static int UpdateProduct(
int productID,
string productName,
int supplierID,
int categoryID,
string quantityPerUnit,
decimal unitPrice,
int unitsInStock,
int unitsOnOrder,
int reorderLevel,
bool discontinued)
{
int rowsAffected = 0;
using (SqlConnection connection = ConnectionManager.GetNorthwindConnection())
{
SqlCommand command = new SqlCommand("ttUpdateProduct", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID;
command.Parameters.Add("#ProductName", SqlDbType.NVarChar, 40).Value = productName;
command.Parameters.Add("#SupplierID", SqlDbType.Int).Value = supplierID;
command.Parameters.Add("#CategoryID", SqlDbType.Int).Value = categoryID;
command.Parameters.Add("#QuantityPerUnit", SqlDbType.NVarChar, 20).Value = quantityPerUnit;
command.Parameters.Add("#UnitPrice", SqlDbType.Money).Value = unitPrice;
command.Parameters.Add("#UnitsInStock", SqlDbType.SmallInt).Value = unitsInStock;
command.Parameters.Add("#UnitsOnOrder", SqlDbType.SmallInt).Value = unitsOnOrder;
command.Parameters.Add("#ReorderLevel", SqlDbType.SmallInt).Value = reorderLevel;
command.Parameters.Add("#Discontinued", SqlDbType.Bit).Value = discontinued;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
using (SqlConnection connection = ConnectionManager.GetNorthwindConnection())
{
SqlCommand command = new SqlCommand("ttUpdateProduct", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID;
command.Parameters.Add("#ProductName", SqlDbType.NVarChar, 40).Value = productName;
command.Parameters.Add("#SupplierID", SqlDbType.Int).Value = supplierID;
command.Parameters.Add("#CategoryID", SqlDbType.Int).Value = categoryID;
command.Parameters.Add("#QuantityPerUnit", SqlDbType.NVarChar, 20).Value = quantityPerUnit;
command.Parameters.Add("#UnitPrice", SqlDbType.Money).Value = unitPrice;
command.Parameters.Add("#UnitsInStock", SqlDbType.SmallInt).Value = unitsInStock;
command.Parameters.Add("#UnitsOnOrder", SqlDbType.SmallInt).Value = unitsOnOrder;
command.Parameters.Add("#ReorderLevel", SqlDbType.SmallInt).Value = reorderLevel;
command.Parameters.Add("#Discontinued", SqlDbType.Bit).Value = discontinued;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
and code for exception handling is
protected void ProductGridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
Master.ErrorMessage = "Cannot Update Record";
e.ExceptionHandled = true;
}
else
{
Master.ResultMessage = "Record Updated Succesfully";
}
but still i am getting error :The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Products_Suppliers". The conflict occurred in database "NORTHWIND", table "dbo.Suppliers", column 'SupplierID'.
The statement has been terminated.
it had worked once ,but not working everytime.
And i am also getting Asp.net Validation of viewstate MAC failed error.
The exception is happening in the stored procedure being called in UpdateProduct so the event RowUpdated is never reached/called so you cannot "catch" that exception there.