简体   繁体   English

想要使用 C# 和 Windows Forms 将两个不同表中的 ID 添加到一个关联表中

[英]Want to add IDs from two different tables into one associative table using C# and Windows Forms

I want to use Windows Forms and C# to implement a Database application which consists of the following tables:我想使用 Windows Forms 和 C# 来实现一个由下表组成的数据库应用程序:

Student table:学生表:

CREATE TABLE [dbo].[Student] (
    [Id]   INT           NOT NULL,
    [Name] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Class table: Class 表:

CREATE TABLE [dbo].[Class] (
    [Id]      INT           NOT NULL,
    [Teacher] NVARCHAR (50) NOT NULL,
    [Grade]   INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

StudentClassCombo:学生班级组合:

CREATE TABLE [dbo].[StudentClassCombo] (
    [ClassID]   INT NOT NULL,
    [StudentID] INT NOT NULL,
    CONSTRAINT [ClassFK] FOREIGN KEY ([ClassID]) REFERENCES [dbo].[Class] ([Id]),
    CONSTRAINT [StudentFK] FOREIGN KEY ([StudentID]) REFERENCES [dbo].[Student] ([Id])
);

I have created a Windows form through which I want to assign students to classes:我创建了一个 Windows 表格,我想通过该表格将学生分配到班级:

在此处输入图像描述

As you can see in the form above, I can successfully populate my combo-box and list view with the expected values.正如您在上面的表格中看到的,我可以成功地使用预期值填充我的组合框和列表视图。 However, I am struggling to implement the functionality for the "Add" button which must assign the checked values in the list view (student names) to the item in the combo-box (Class) and add the mappings to the table StudentClassCombo .但是,我正在努力实现“添加”按钮的功能,该按钮必须将列表视图(学生姓名)中的选中值分配给组合框(类)中的项目,并将映射添加到表StudentClassCombo

My code for the button-click event is as follows:我的按钮单击事件代码如下:

private void student2class_Click(object sender, EventArgs e)
        {
            

            string insertCommand = "INSERT INTO dbo.StudentClassCombo (ClassID, StudentID) "
    + "(SELECT Id FROM dbo.Class "
    + "WHERE Grade = @Grade)"
    + "(SELECT Id FROM dbo.Student "
    + "WHERE Name = @StudentName)";

            using (connection = new SqlConnection(connectionString))
            using (SqlCommand Insertcmd = new SqlCommand(insertCommand, connection))
            {
                Insertcmd.Parameters.Add("@Grade", SqlDbType.Int);
                Insertcmd.Parameters.Add("@StudentName", SqlDbType.NVarChar, 50);

                connection.Open();

                foreach (ListViewItem eachItem in StudentsList.CheckedItems)
                {
                    //string Selected = eachItem.SubItems[0].Text; //directly access "eachItem"

                    Insertcmd.Parameters["@Grade"].Value = int.Parse(ClassNames.Text);
                    Insertcmd.Parameters["@StudentName"].Value = eachItem.SubItems[0].Text;

                    Insertcmd.ExecuteNonQuery();
                }

                connection.Close();
            }
            
        }
    }

But when I run the above code, I run into the following exception:但是当我运行上面的代码时,我遇到了以下异常:

The select list for the INSERT statement contains fewer items than the insert list. INSERT 语句的 select 列表包含的项目少于插入列表。 The number of SELECT values must match the number of INSERT columns. SELECT 值的数量必须与 INSERT 列的数量匹配。

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.

There are two SELECT statements in my query.我的查询中有两个SELECT语句。 I do not understand why the program is not recognizing both of them?我不明白为什么程序不能同时识别它们?

I looked at the insert statement quickly and appear to incorrect.我快速查看了插入语句,似乎不正确。

Change from:更改自:

string insertCommand = "INSERT INTO dbo.StudentClassCombo (ClassID, StudentID) "
    + "(SELECT Id FROM dbo.Class "
    + "WHERE Grade = @Grade)"
    + "(SELECT Id FROM dbo.Student "
    + "WHERE Name = @StudentName)";

To:至:

string insertCommand = @"INSERT INTO dbo.StudentClassCombo (ClassID, StudentID) VALUES ((SELECT Id FROM dbo.Class WHERE Grade = @Grade), (SELECT Id FROM dbo.Student WHERE Name = @StudentName))";

You are missing a comma after the first Select statement第一个 Select 语句后缺少逗号

The other two answers resolve the error you're experiencing but in terms of how we would typically structure an app, you'd download both the Id and the Grade (and the Id and StudentName) and you'd store both locally in some associated way.其他两个答案解决了您遇到的错误,但就我们通常如何构建应用程序而言,您将同时下载 Id 和 Grade(以及 Id 和 StudentName),并将两者都存储在本地方法。 When the user choose "John" you will already know which ID it relates to and you'd just insert that ie当用户选择“John”时,您将已经知道它与哪个 ID 相关,您只需插入即

INSERT INTO dbo.StudentClassCombo (ClassID, StudentID) VALUES ( @GradeId, @StudentId )

You wouldn't have this "look up the ID based on the name the user picked in the ui" process, especially as it's prone to fail if there are two entries with the same name您不会有这种“根据用户在 ui 中选择的名称查找 ID”过程,特别是如果有两个具有相同名称的条目很容易失败

Most windows list type controls that can be bound to a list of items have a facility for declaring which property holds the text to be displayed and which holds a value to use as the ID.大多数可以绑定到项目列表的 windows 列表类型控件都具有声明哪个属性保存要显示的文本以及哪个保存用作 ID 的值的功能。 For example a listbox set up like:例如一个列表框设置如下:

lb.DisplayMember = "StudentName";
lb.ValueMember = "Id";
lb.DataSource = someStudentDataTable;

will associate with a bunch of student rows in a datatable, show the name but whenever the listbox is asked for the SelectedValue the ID of the selected student is returned将与数据表中的一堆学生行相关联,显示名称,但每当要求列表框提供 SelectedValue 时,都会返回所选学生的 ID

Try this query string:试试这个查询字符串:

 string insertCommand = "INSERT INTO dbo.StudentClassCombo (ClassID, StudentID) "
+ "SELECT Class.ID as ClassId, Student.Id as StudentId from dbo.Class,dbo.Student"+ 
" where Class.Grade=@Grade and Student.Name = @StudentName";

and fix the parameters并修复参数

 Insertcmd.Parameters.Add("@Grade", SqlDbType.Int).Value=0;
Insertcmd.Parameters.Add("@StudentName", SqlDbType.NVarChar).Value=string.Empty;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM