如何修复c#中键约束的重复?

如何修复c#中键约束的重复?,c#,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; 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中添加空格,我该如何修复该按钮,或者提示一些警告

如果您已将Student\u ID字段设置为数据库中的主键,则无需将其包含在insert语句中,您只需在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 + "')";

执行以下步骤以解决您的问题

1_在数据库中将主键设置为
自动增加

2\u像这样更改代码

"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 + "')";

删除
Student\u ID
textBox2.Text

将您的主键设置为自动增加DB,并从Insert INTO中删除此ID。因此,我认为当您从用户处获得主键时,通常会引发重复异常!那么,如果它的Id已经存在,您的计划是什么呢?请阅读SQL注入。使用原始用户输入编写SQL查询是编写安全漏洞的最简单方法之一。这会显示学生id吗?因为我需要在我的输出中显示它。是的,你可以在绑定你的网格时得到它,而不是在你想插入数据库时使用它