Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7640419
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T08:40:00+00:00 2026-05-31T08:40:00+00:00

my error is simple but for me it is hard to fix it because

  • 0

my error is simple but for me it is hard to fix it because my knowledge is not good . which is when i Enter the record by clicking the Addbutton of AddStudent record then the record that i deleted like record StudentID = 1, FirstName =Raju ,LastName=Abbasi

After Delete it again and press save Change even After that when i again try to use the ID=1 means enter the Record with ID=1 that i have been deleted and record the StudentID=1 ,FirstName =Ram ,LastName=Rakish .Then error is occur which is


    private static SqlDataAdapter CreateSutdentDataAdapter()
           {

               string gettSQL = "SELECT * FROM Student";

               string insertSQL = "SET IDENTITY_INSERT Student ON;INSERT INTO Student(StudentID, FirstName,LastName,Gender,GPA,MyImage)" +
                   "VALUES (@StudentID,@FirstName,@LastName,@Gender,@GPA,@MyImage);SET IDENTITY_INSERT Student OFF";
              string updateSQL = "UPDATE Student SET  FirstName=@FirstName,LastName=@LastName ,Gender=@Gender, MyImage=@MyImage," +
                " GPA=@GPA WHERE StudentID=@StudentID";
               string deleteSQL = "DELETE FROM Student WHERE StudentID=@StudentID";

               SqlDataAdapter dataAdapter = new SqlDataAdapter();

               dataAdapter.SelectCommand = new SqlCommand(gettSQL, ConnectionManager.GetConnection());

               dataAdapter.InsertCommand = new SqlCommand(insertSQL, ConnectionManager.GetConnection());

               dataAdapter.InsertCommand.Parameters.Add("@StudentID", SqlDbType.Int).SourceColumn = "StudentID";
               dataAdapter.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
               dataAdapter.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
               dataAdapter.InsertCommand.Parameters.Add("@Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
               dataAdapter.InsertCommand.Parameters.Add("@GPA", SqlDbType.Float ).SourceColumn = "GPA";
               dataAdapter.InsertCommand.Parameters.Add("@MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";

               dataAdapter.UpdateCommand = new SqlCommand(updateSQL, ConnectionManager.GetConnection());
               dataAdapter.UpdateCommand.Parameters.Add("@StudentID", SqlDbType.Int).SourceColumn = "StudentID";
               dataAdapter.UpdateCommand.Parameters.Add("@FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
               dataAdapter.UpdateCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
               dataAdapter.UpdateCommand.Parameters.Add("@Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
               dataAdapter.UpdateCommand.Parameters.Add("@GPA", SqlDbType.Float ).SourceColumn = "GPA";
               dataAdapter.UpdateCommand.Parameters.Add("@MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
               dataAdapter.DeleteCommand = new SqlCommand(deleteSQL, ConnectionManager.GetConnection());
               dataAdapter.DeleteCommand.Parameters.Add("@StudentID", SqlDbType.Int).SourceColumn = "StudentID";

               return dataAdapter;

           }

       private static void DefinestudentTableSchema(DataTable table)
       {
           DataColumn StudentIDColumn = table.Columns.Add("StudentID", typeof(string));
           StudentIDColumn.AllowDBNull = false;

           table.PrimaryKey = new DataColumn[] { StudentIDColumn };

           DataColumn StudentFirstName = table.Columns.Add("FirstName", typeof(string));
           StudentFirstName.MaxLength = 150;
           DataColumn StudentLastName = table.Columns.Add("LastName", typeof(string));
           StudentLastName.MaxLength = 150;
           DataColumn StudentGender = table.Columns.Add("Gender", typeof(string ));

          DataColumn StudentGPA = table.Columns.Add("GPA", typeof(string ));
          DataColumn StudentImage = table.Columns.Add("MyImage", typeof(Byte[]));

       }
       private static DataSet CreateStudentTrackerDataSet()
       {
           DataSet StudentTrackerDataSet = new DataSet();
           DataTable StudentTable = StudentTrackerDataSet.Tables.Add("Student");
           DefinestudentTableSchema(StudentTable);
           return StudentTrackerDataSet;
       }

       public static DataSet GetData()
       { 
           DataSet StudentTrakerDataSet = CreateStudentTrackerDataSet();
           StudentTrakerDataSet.EnforceConstraints = false;
           StudentDataAdapter.Fill(StudentTrakerDataSet.Tables["Student"]);

           StudentTrakerDataSet.EnforceConstraints = true;
           return StudentTrakerDataSet;
       }

        public AddModifyStudentRecords(DataSet ds, DataRow row)
        {
public static void SaveData(ref DataSet changesDataSet)
       {
           DataSet addedDataSet = changesDataSet.GetChanges(DataRowState.Added);
           if (addedDataSet != null)
           {
               StudentDataAdapter.Update(addedDataSet.Tables["Student"]);
               changesDataSet.Merge(addedDataSet); // Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
           }
           DataSet modifiedDataSet = changesDataSet.GetChanges(DataRowState.Modified);
           if (modifiedDataSet != null)
           {
               StudentDataAdapter.Update(modifiedDataSet.Tables["Student"]);
               changesDataSet.Merge(modifiedDataSet);
           }
           DataSet deletedDataSet = changesDataSet.GetChanges(DataRowState.Deleted);
           if (deletedDataSet != null)
           {
               StudentDataAdapter.Update(deletedDataSet.Tables["Student"]);
             deletedDataSet.Merge(deletedDataSet);
           }

here is my Addmodifyform logic for add the StudentID

public partial class AddModifyStudentRecords : Form
    { 

        DataSet StudentTrackerDataSet;
        DataRow currentRow;


        public AddModifyStudentRecords()
        {
            InitializeComponent();
        }

        public AddModifyStudentRecords(DataSet ds)
        {
            InitializeComponent();
            StudentTrackerDataSet = ds;
            currentRow = null;
        }
    public AddModifyStudentRecords(DataSet ds, DataRow row) 
    {
    InitializeComponent(); 
    StudentTrackerDataSet = ds; 
    currentRow = row;
    textBox1.Text =currentRow["StudentID"] .ToString(); 
    textBox2.Text = currentRow["FirstName"].ToString(); 
    textBox4.Text = currentRow["LastName"].ToString(); 
    textBox3.Text = currentRow["Gender"].ToString(); 
    textBox5.Text = currentRow["GPA"].ToString(); 
    txtBrowseFile.Text = currentRow["MyImage"].ToString (); 
    byte[] data = (byte[])currentRow ["MyImage"]; 
    MemoryStream ms = new MemoryStream(data); 
    pictureBox1.Image = Image.FromStream(ms); 
    string StudentID = textBox1.Text.ToString(); 
    string StudentFirstName = textBox2.Text.ToString(); 
    string StudentLastName = textBox4.Text.ToString(); 
    string Gender = textBox3.Text.ToString(); 
    string GPA = textBox5.Text.ToString(); 
    Image MyImage = pictureBox1.Image; 
    DataTable table = StudentTrackerDataSet.Tables["Student"]; 
    if (currentRow == null) {
    currentRow = table.NewRow(); 
    currentRow["StudentID"] = textBox1.Text.ToString(); 
    table.Rows.Add(currentRow ); 
    } 
    currentRow .BeginEdit();
    currentRow ["StudentID" ]=StudentID ; 
    currentRow["FirstName"] = StudentFirstName; 
    currentRow["LastName"] = StudentLastName; 
    currentRow["Gender"] = Gender; 
    currentRow["GPA"] = GPA; 
    currentRow["MyImage"] = convertToByte(txtBrowseFile.Text); 
    currentRow.EndEdit(); 
    Close();
   } 

public partial class AditStudent : Form
{
// Creat the Class variabl Dataset to track the Student
private DataSet StudentTrackerDataset;

        public AditStudent()
        {
            InitializeComponent();

            dataGridView1.DataError += DataGridView1_DataError;
            StudentTrackerDataset = ProjectOfSchool.DataAccessLayer.DAC.GetData();

            DataTable StudentTable = StudentTrackerDataset.Tables["Student"];

            dataGridView1.DataSource = StudentTable;
            //StudentTable.Columns["ID"].AutoIncrement = true;
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
                if (dataGridView1.Columns[i] is DataGridViewImageColumn)
                {
                    ((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
                    break;
                }
        }
        private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

            string message = string.Format("Error in {0} columan in row {1}:{2}", e.ColumnIndex, e.RowIndex, e.Exception.Message);

            MessageBox.Show(message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            AddModifyStudentRecords AddStudent = new AddModifyStudentRecords(StudentTrackerDataset);
            AddStudent.ShowDialog();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
            DataRow StudentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
            AddModifyStudentRecords modifyStudent = new AddModifyStudentRecords(StudentTrackerDataset, StudentRow);
            modifyStudent.ShowDialog();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure", "Delete Current Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
                DataRow currentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
                currentRow.Delete();
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (!StudentTrackerDataset.HasChanges())
            {
                MessageBox.Show("There are no Change to Save ", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                try
                {
                    DataSet changesDateSet = StudentTrackerDataset.GetChanges();
                    ProjectOfSchool.DataAccessLayer.DAC.SaveData(ref changesDateSet);
                    StudentTrackerDataset.Merge(DAC.GetData());
                    MessageBox.Show("Data Save Successfully.", "Save Changes");
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Data Not Saved:" + ex.Message, "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            if (!StudentTrackerDataset.HasChanges())
            {
                MessageBox.Show("There are no Changes to Save.", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                DialogResult result = MessageBox .Show ("Are you Sure?","Reject Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes )
                {
                    StudentTrackerDataset.RejectChanges();
                }
            }
        }

And When i terminate the program and re execute the program then i saw that StudntID=1 is also save to Database with ID=1

or When i Delete the StudentID =1 and press save Change after press save Change when i also Terminate the program and re exicute the program and after that when i Enter the StudentID =1 Then no error is occur

And other way without termination is to Delete the record StudentID1 but when you Add the Student record but not Add the StudentID=1 But add the StudentID other then 1 in this case error is also not happend . Dear Sherik I have been solve my other error but i have still error which is in my Tittle So please responding me for this error And i re edited my code also So please replay me Thanks

I have record in my Database which have following Datatype as

StudentID=INT,

FirstName=VarChar,

LastName=VarChar,

Gender=Varchar,

GPA=Float,

MyImage=Vabinary (MAX)

Or may be Datarow fail to Delete the record or Update the record. I don’t know please tell me and thanks to reply me and I am waiting for your reply.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T08:40:01+00:00Added an answer on May 31, 2026 at 8:40 am

    The error message seems to indicate that you are hitting a Primary Key constraint.
    I would suggest that you first stop allowing the user to enter the Student ID field. Let it be generated as an auto increment key in whatever database you are using. In Access, it is called AutoNumber.

    Once you have done that, re test and post the results.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This may seem like a simple question but i am getting an error when
I'm sending a simple mail with attachment using SmtpClient but I get this error:
This might seem ridiculously simple, but I've been getting all kinds of error depending
This sure seems like a simple error to fix. However, I somehow can't figure
I can not get to make this comparison in this simple code error ..
Im trying to make a quite simple game but its having an error. I
I tried to compile Ercia Sadun's sample code here , but this error came
I've got probably what is a simple problem, but there's no informative errors or
What would be the best way to implement a simple crash / error reporting
Something as simple as: $(#div).addClass(error).delay(1000).removeClass(error); doesn't seem to work. What would be the easiest

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.