I want to use Windows Forms and C# to implement a Database application which consists of the following tables:
Student table:
CREATE TABLE [dbo].[Student] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Class table:
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:
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
.
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. The number of SELECT values must match the number of INSERT columns.
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. I do not understand why the program is not recognizing both of them?