检查DropDownList的选定值是否存在于数据库中的问题

时间:2019-04-23 11:06:11

标签: c# asp.net

我有一个网页,并且我有一些字段可以保存一些数据。

其中一个字段保留注册特定课程的学生的ID和姓名。我希望能够通过使用DropDownList向课程注册新学生。如果课程表中已经存在DropDownList中的选定项目,我应该显示一条错误消息。我有执行这些操作的代码,但是当我在下拉列表中选择一个已经存在的值时,它不会显示错误消息。它假定这是一个新值,并且因为数据库不接受重复的记录而引发异常。

我该如何解决此问题?

我使用c#语言在ASP.NET中设计此网页。

    protected void DropDownList1_SelectedIndexChanged(object sender, 
    EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True");


        string qs = Request.QueryString["id"]; 
        // Variable qs Keeps CourseID retrieved from query string

        string sv = DropDownList1.SelectedItem.Value; 
        // Variable sv keeps selected value from DropDownList


        SqlCommand cmd = new SqlCommand("Select * from Enrolment as e, Students as s where e.StudentID = s.StudentID and " +
                          "CourseID = " + qs + " and StudentName = '" + sv +"'", con);
        // There are Students, Courses, and Enrolment tables in database
        // Students table columns are StudentID, StudentName, BirthDate
        // Course table columns are CourseID, CourseCode, CourseName, Instructor
        // Enrolment table columns are CourseID and StudentID


        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        if(reader.HasRows)
        {
            Label1.Visible = true;
            Label1.Text = "The selected student is already registered to the course!";
            Label1.ForeColor = Color.Red;
        }
        else
        {
            Label1.Visible = true;
            Label1.Text = "The selected student is succesfully registered!";
            Label1.ForeColor = Color.Green;


            SqlDataSource4.Insert();
            GridView1.DataBind();
        }

        reader.Close();
        con.Close();
    }

当我从DropDownList中选择一个数据库中不存在的名称时,我会得到正确的结果。

例如,考虑“ Jeff Bezos”已经为给定课程注册。当我选择“杰夫·贝佐斯”时,我应该收到错误消息,但会收到异常消息,说明重复。

3 个答案:

答案 0 :(得分:1)

  1. 参数化sql
  2. 使sql成为字符串/文本并使用它
  3. 如果关联联接不好,请摆脱它,而是创建一个INNER
  4. 使用实现了idisposable的using
  5. 假设您没有发布列表的来源
  6. 关于id的int vs字符串的广泛假设(int是最常见的,所以我同意)
  7. 建议将其重构为更好的测试方法
       using System;
       using System.Data.SqlClient;
        // more here likely...
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True";
            string getStudentIdSql = @"
                SELECT s.StudentID 
                FROM Enrolment AS e
                INNER JOIN Students AS s 
                    ON e.StudentID = s.StudentID 
                    AND E.CourseID = @CourseID
                    AND StudentName = @StudentName
            ";
            int courseId = int.Parse(Request.QueryString["id"]); // consider tryparse here, I make assumptions on the int also
            // string studentName = DropDownList1.SelectedItem.Value; // assumption if the values are there
            string studentName = DropDownList1.SelectedItem.Text; // assumption based on code/comments, key part where it is defined is missing from question
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(getStudentIdSql, conn))
                {
                    cmd.Parameters.Add("@CourseID", SqlDbType.Int).Value = courseId;
                    cmd.Parameters.Add("@StudentName", SqlDbType.VarChar, 80).Value = studentName;
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        /* if we wanted to have the rows
                    while (reader.Read())
                    {
                        Console.WriteLine($"{reader.GetInt32(0)}\t{ reader.GetString(1)}");
                    }
                    */
                        Label1.Visible = true;
                        Label1.Text = "The selected student is already registered to the course!";
                        Label1.ForeColor = Color.Red;
                    }
                    /* basic thing
                else
                {
                    Console.WriteLine("No rows found.");
                }
                */
                    else
                    {
                        Label1.Visible = true;
                        Label1.Text = "The selected student is succesfully registered!";
                        Label1.ForeColor = Color.Green;
                        SqlDataSource4.Insert();
                        GridView1.DataBind();
                    }

                    reader.Close();
                }
            }
        }

答案 1 :(得分:0)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="button-container">
  <button class="black-button"></button>
  <button class="red-button"></button>
  <button class="blue-button"></button>
  <button class="yellow-button"></button>
</div>

<button id="flash-toggle" onclick="$('.bar1').toggleClass('blinking')">
    Toggle Blinking
</button>
<img id="bar" class="bar1" src="flash-red.png" alt="bar" >

答案 2 :(得分:0)

ID是我数据库中的整数值,因此我将qs的类型更改为int
        int qs = int.Parse(Request.QueryString["id"]);

下面的代码部分也应该像         string sv = DropDownList1.SelectedItem.Text;

更改这些代码后,我得到了真实的结果