-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

aman
  • 17
  • 4
  • 2
    You have 3 queries here, and you have conveniently left out which query is causing the problem . however your delete query is munted, and is susceptible to an sql injection attack. Also the insert query could be failing as well. consider using parameterized queries and double check the sql – TheGeneral Feb 07 '21 at 01:42
  • 5
    @00110001 means to say it should be `delete from PatTbl where PatID=` and you should really use SQL parameters to avoid injection. Other issues: you need to dispose the connection, command, adapter etc objects with `using`, don't cache the connection object. Also, specify the columns you are inserting into like `insert into table (col1,col2) values (...` Also, [AttachDbFileName is going to cause issues](https://stackoverflow.com/questions/11178720/whats-the-issue-with-attachdbfilename). Also, don't block with `MessageBox` or do heavy processing while the connection is open – Charlieface Feb 07 '21 at 01:53
  • 3
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should ***NEVER EVER*** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Feb 07 '21 at 07:38
  • thank u all for your comments, i have edited the code, can you please re-check it? – aman Feb 07 '21 at 11:35
  • your insert statement is wrong, it should be something like this INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); – Nonik Feb 10 '21 at 01:29

1 Answers1

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 :)