我必须在此代码中纠正什么? [英] what must i rectify in this code?

查看:64
本文介绍了我必须在此代码中纠正什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button1_Click(object sender, EventArgs e)
        {
            command.Parameters.AddWithValue("@StudentID", textBox1.Text);
            command.Parameters.AddWithValue("@Name", textBox2.Text);
            command.Parameters.AddWithValue("@Age", textBox3.Text);
            command.Parameters.AddWithValue("@Gender", textBox4.Text);
            command.Parameters.AddWithValue("@Courseno",comboBox1.Text);
            command.CommandText = "INSERT into details"+ "(StudentID,Name,Age,Gender,Courseno)VALUES" + "(@StudentID,@Name,@Age,@Gender,@Courseno)";

            try
            {
                con.Open();

                int result = command.ExecuteNonQuery();

                if (result > 0)
                    MessageBox.Show("student successfully updated");
                else
                    MessageBox.Show("failed to update");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }

            ClearFields();
        }



当我输入一组详细信息并单击按钮时,它将更新数据库.但是我第二次无法输入第二组详细信息.它说@StudentID已经被声明.



When i enter one set of details and click the button, it updates the database. but I am unable to enter a second set of details the second time around. It says @StudentID has already been declared.

推荐答案

添加
command.Parameters.Clear();





private void button1_Click(object sender, EventArgs e)
        {
            command.Parameters.AddWithValue("@StudentID", textBox1.Text);
            command.Parameters.AddWithValue("@Name", textBox2.Text);
            command.Parameters.AddWithValue("@Age", textBox3.Text);
            command.Parameters.AddWithValue("@Gender", textBox4.Text);
            command.Parameters.AddWithValue("@Courseno",comboBox1.Text);
            command.CommandText = "INSERT into details"+ "(StudentID,Name,Age,Gender,Courseno)VALUES" + "(@StudentID,@Name,@Age,@Gender,@Courseno)";

            try
            {
                con.Open();

                int result = command.ExecuteNonQuery();

                if (result > 0)
                    MessageBox.Show("student successfully updated");
                else
                    MessageBox.Show("failed to update");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
                command.Parameters.Clear()
            }

            ClearFields();
        }


这篇关于我必须在此代码中纠正什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆