首页 > 解决方案 > 如何修复 C# 中键约束的重复?

问题描述

这是我的代码,

//Set  the property AllowUserToAddRows to false will prevent a new empty row
dataGridView1.AllowUserToAddRows = false;

//registration of students 
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO TableStudents(Student_ID,Fullname,Gender,Course,Year,Section,Guardian,Contact,Address)VALUES('" + textBox2.Text + "','" + textBox1.Text + "','" + ComboBox4.Text + "','" + ComboBox1.Text + "','" + ComboBox2.Text + "','" + ComboBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')";

cmd.ExecuteNonQuery();

connect.Close();

当我尝试单击我的注册按钮时,我的datagridview中出现了一个空格,那么如果它总是在datagridview中添加一个空格,我该如何修复注册按钮或者提示一些警告
在此处输入图像描述

标签: c#

解决方案


如果您已将 Student_ID 字段设置为数据库中的主键,则无需将其包含在插入语句中,您可以简单地排除或使该字段在 Datagrid 中不可见:

cmd.CommandText = "INSERT INTO TableStudents(Fullname,Gender,Course,Year,Section,Guardian,Contact,Address)VALUES(textBox1.Text + "','" + ComboBox4.Text + "','" + ComboBox1.Text + "','" + ComboBox2.Text + "','" + ComboBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')";

推荐阅读