Visual Studio 2012 - 参数在插入时没有默认值错误

本文关键字:默认值 错误 插入 Studio 2012 参数 Visual | 更新日期: 2023-09-27 18:33:04

我有一个Windows应用程序,它正在将数据插入到Access数据库中。但是,我遇到以下错误:

参数@IMajor没有默认值。

提前谢谢你。这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace InterestCardNew
{
    public partial class Form1 : Form
    {
        public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'interestDataSet.InterestCard' table. You can move, or remove it, as needed.
        this.interestCardTableAdapter.Fill(this.interestDataSet.InterestCard);
        lblCurrentDate.Text = DateTime.Now.ToShortDateString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data     Source=C:'Temp'Interest.accdb";
        OleDbConnection con = new OleDbConnection(conString);
        OleDbCommand cmd = con.CreateCommand();
        string text = "INSERT INTO InterestCard (FirstName, LastName, StreetAddress, City, State, ZipCode, Phone, Email, DOB, Gender, HighSchool, GraduationYear, PlannedTerm, IntendedMajor) VALUES (@FName, @LName, @SAddress, @City, @State, @Zip, @Phone, @Email, @DOB, @Gender, @HSchool, @GradYear, @PTerm, @IMajor)";
        cmd.CommandText = text;
            con.Open();
            cmd.Parameters.AddWithValue("@FName", txtFirstName.Text);
            cmd.Parameters.AddWithValue("@LName", txtLastName.Text);
            cmd.Parameters.AddWithValue("@SAddress", txtAddress.Text);
            cmd.Parameters.AddWithValue("@City", txtCity.Text);
            cmd.Parameters.AddWithValue("@State", txtState.Text);
            cmd.Parameters.AddWithValue("@Zip", txtZipCode.Text);
            cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
            cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@DOB", dtpDOB.Value);
            cmd.Parameters.AddWithValue("@Gender", rbFemale.Checked);
            cmd.Parameters.AddWithValue("@HSchool", txtHighSchool.Text);
            cmd.Parameters.AddWithValue("@GradYear", txtGraduationYear.Text);
            cmd.Parameters.AddWithValue("@PTerm", txtTermofEnrollment.Text);
            cmd.Parameters.AddWithValue("@IMajor", cbIntendedMajor.SelectedValue);
            cmd.ExecuteNonQuery();

        }

    }
}   

Visual Studio 2012 - 参数在插入时没有默认值错误

具有null值的参数将被忽略,在您的情况下,cbIntendedMajor.SelectedValue似乎是null的。如果此处应允许null,则必须将其替换为 DBNull.Value ,这将导致参数在执行查询时具有预期的 null 值。例:

cmd.Parameters.AddWithValue("@IMajor", (object)cbIntendedMajor.SelectedValue ?? DBNull.Value);