Adding data to SQL Server results in System.Data.SqlClient.SqlException: 'Invalid column name'

-2

I'm totally new to C# and SQL Server. I'm building a simple program where it has patients and their data should be presented on the screen after it entered by the user but whenever I try to add data to the database I get this error:

System.Data.SqlClient.SqlException: 'Invalid column name

Here is my code

   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.SqlClient;

namespace WindowsFormsApp1
{
    public partial class Patients: Form
    {
        SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\SAMSUNG\Documents\MHSdb.mdf;Integrated Security=True;Connect Timeout=30");
        public Patients()
        {
            InitializeComponent();
        }
        void populate()
        {
            Con.Open();
            string query = " select * from PatientsTable";
            SqlDataAdapter da = new SqlDataAdapter(query, Con);
            SqlCommandBuilder builder = new SqlCommandBuilder(da);
            var view = new DataSet();
            da.Fill(view);
            PatGV.DataSource = view.Tables[0];
            Con.Close();
        }
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            this.Hide();
            Home h = new Home();
            h.Show();
        }

        private void textBox12_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Con.Open();
            string query = "insert into PatientsTable values(" + PatID.Text + ", " + PatName.Text + "," + FileNumber.Text + "," + CitizenID.Text + "," + Gender.Text + ", " + Birthdate.Text + ", " + Nationality.Text + ", " + PhoneNum.Text + ", " + Email.Text + "," + Country.Text + "," + City.Text + "," + Street.Text + "," + Address1.Text + "," + Address2.Text + "," + ContactPerson.Text + "," + ContactRelation.Text + "," + ContactPhone.Text + ", " + FirstVIstit.Text + "," + c.Text + ")";
            SqlCommand cmd = new SqlCommand(query, Con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Patient Added Sucecsfully");
            Con.Close();
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Home h = new Home();
            h.Show();
            this.Hide();
        }

        private void PatGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            populate();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (PatID.Text == "")
                MessageBox.Show("Enter the Patient ID");
            else
            {
                Con.Open();
                string query = "delete from PatientsTable where PatID" + PatID.Text + "";
                SqlCommand cmd = new SqlCommand(query, Con);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Patient deleted Successfully!");
                Con.Close();
                populate();
            }
        }

        private void PatID_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

here is my database code

 CREATE TABLE [dbo].[PatientsTable] (
    [PatId]                 INT       NOT NULL,
    [PatientName]               CHAR (10) NOT NULL,
    [FileNumber]             INT       NOT NULL,
    [CitizenID]          CHAR (10) NOT NULL,
    [Birthdate]           DATE      NULL,
    [Nationality]        CHAR (10) NOT NULL,
    [PhoneNum]        INT       NOT NULL,
    [Email]              CHAR (10) NULL,
    [Country]            CHAR (10) NOT NULL,
    [City]               CHAR (10) NOT NULL,
    [Street]             CHAR (10) NOT NULL,
    [Address1]               CHAR (10) NOT NULL,
    [Address2]               CHAR (10) NOT NULL,
    [ContactPerson]      CHAR (10) NOT NULL,
    [ContactRelation]    CHAR (10) NOT NULL,
    [ContactPhone]       INT       NOT NULL,
    [FirstVIstit]     DATE      NULL,
    [RecordCreationDate] DATE      NULL,
    [Gender]             CHAR (10) NULL,
    PRIMARY KEY CLUSTERED ([PatientsTable] ASC)
);

here is the error log

    System.Data.SqlClient.SqlException
  HResult=0x80131904
  Message=Invalid column name 'yaman'.
Invalid column name 'Male'.
Invalid column name 'sytian'.
Invalid column name 'yam'.
Invalid column name 'uwei'.
Invalid column name 'gt'.
Invalid column name 'uywyr'.
Invalid column name 'ywry'.
Invalid column name 'fbk'.
Invalid column name 'lina'.
Invalid column name 'fanily'.
  Source=.Net SqlClient Data Provider
  StackTrace:
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at WindowsFormsApp1.Patients.button4_Click(Object sender, EventArgs e) in C:\Users\SAMSUNG\source\repos\WindowsFormsApp1\WindowsFormsApp1\Patients.cs:line 49
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at WindowsFormsApp1.Program.Main() in C:\Users\SAMSUNG\source\repos\WindowsFormsApp1\WindowsFormsApp1\Program.cs:line 19

I have looked in other questions but looks like there is none like my question

c#
.net
sql-server
asked on Stack Overflow Feb 7, 2021 by aman • edited Feb 7, 2021 by aman

1 Answer

1

I think the problem comes from this line

string query = "insert into PatientsTable values(" + PatID.Text + ", " + PatName.Text + "," + FileNumber.Text + "," + CitizenID.Text + "," + Gender.Text + ", " + Birthdate.Text + ", " + Nationality.Text + ", " + PhoneNum.Text + ", " + Email.Text + "," + Country.Text + "," + City.Text + "," + Street.Text + "," + Address1.Text + "," + Address2.Text + "," + ContactPerson.Text + "," + ContactRelation.Text + "," + ContactPhone.Text + ", " + FirstVIstit.Text + "," + c.Text + ")";

you must add apostrophe in the text type fields as follow :

string query = "insert into PatientsTable values(" + PatID.Text + ", '" + PatName.Text + "'," + FileNumber.Text + ",'" + CitizenID.Text + "','" + Gender.Text + "', '" + Birthdate.Text + "', '" + Nationality.Text + "', " + PhoneNum.Text + ", '" + Email.Text + "','" + Country.Text + "','" + City.Text + "','" + Street.Text + "','" + Address1.Text + "','" + Address2.Text + "','" + ContactPerson.Text + "','" + ContactRelation.Text + "'," + ContactPhone.Text + ", " + FirstVIstit.Text + "," + c.Text + ")";

Also, you must insert the data in order, for example in your insert line code, "gender" is in the 5th position, but in your table structure "gender" is in the last position. so you need to edit your line code by adding more information like this :

"insert into [dbo].[PatientsTable] (PatID, PatName, FileNumber, CitizenID, Gender, Birthdate ...add all the column...) values (" + PatID.Text + ", '" + PatName.Text + "'," + FileNumber.Text + ",'" + CitizenID.Text + "','" + Gender.Text + "', '" + Birthdate.Text + "', '" + Nationality.Text + "', " + PhoneNum.Text + ", '" + Email.Text + "','" + Country.Text + "','" + City.Text + "','" + Street.Text + "','" + Address1.Text + "','" + Address2.Text + "','" + ContactPerson.Text + "','" + ContactRelation.Text + "'," + ContactPhone.Text + ", " + FirstVIstit.Text + "," + c.Text + ")"; 

also, you need to add a condition in this line like (=) or (like), and put the Quotes in the right position

string query = "delete from PatientsTable where PatID" + PatID.Text + "";

like that

string query = "delete from PatientsTable where PatID =" + PatID.Text;

i hope i helped you :)

answered on Stack Overflow Feb 10, 2021 by missipssa marsh

User contributions licensed under CC BY-SA 3.0