Reputation: 3
Have just started working with C# and sql and have been trying to use a database to store information, but not 100% on the syntax of it all and have been piecing it together, but have not been able to get past this error, any help would be appreciated, it is probably only something simple i have looked over.
here is the C# code i am using to try and access the database
SqlConnection myConnection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=""F:\Bar admin\Bar admin\Database.mdf"";Integrated Security=True");
SqlCommand DatabaseNew = new SqlCommand("insert into Events Values(@Name, @Date, @Price, @Tickets, @Descrip)");
myConnection.Open();
// adds the event information to the database
DatabaseNew.Parameters.AddWithValue("@Name", TxtName.Text);
DatabaseNew.Parameters.AddWithValue("@Date", dateTimePicker1.Value);
DatabaseNew.Parameters.AddWithValue("@Price", TxtName.Text);
DatabaseNew.Parameters.AddWithValue("@Tickets", Convert.ToInt16(TxtTicketNum.Text));
DatabaseNew.Parameters.AddWithValue("@Descrip", TxtDesc.Text);
DatabaseNew.Connection = myConnection;
int n = DatabaseNew.ExecuteNonQuery();
if (n>0)
{
MessageBox.Show("Event" + TxtName.Text + "Added");
}
myConnection.Close();
and the sql code
CREATE TABLE [dbo].[Events] (
[Id] INT NOT NULL,
[Name] NCHAR (10) NULL,
[Date] DATETIME NULL,
[Price] NCHAR(10) NULL,
[Tickets] INT NULL,
[TicketsSold] INT NULL,
[Descrip] NVARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Again any help would be much apreaciated, thank you.
Upvotes: 0
Views: 633
Reputation: 4737
It is expecting all fields with exact order. So Id and TicketsSold are missing and causing error. You should change to:
SqlCommand DatabaseNew = new SqlCommand("insert into Events
(Name,Date,Price,Tickets,Decrip) Values(@Name, @Date, @Price, @Tickets, @Descrip)");
Upvotes: 3
Reputation: 223247
You are not passing ID
and it doesn't appear that your ID is set to Auto increment.
Upvotes: 3