none
System.InvalidCastException: 'Specified cast is not valid.' RRS feed

  • Question

  • Hi i am creating a IT Inventory application in visual studio community 2017 , the code is in asp.net / C#. When i submit the data to the SQL table i received this error 

    System.InvalidCastException: 'Specified cast is not valid.'

    my sql table query is:

    CREATE TABLE [dbo].[Workstations](
    [Emp_Id] [int] IDENTITY(1,1) NOT NULL,
    [Emp_Name] [varchar](30) NOT NULL,
    [Emp_Surname] [varchar](30) NOT NULL,
    [Department] [varchar](50) NOT NULL,
    [Company] [varchar](30) NOT NULL,
    [Hostname] [nvarchar](20) NOT NULL,
    [Wkst_Status] [varchar](15) NOT NULL,
    [Make] [varchar](12) NOT NULL,
    [Model] [varchar](15) NOT NULL,
    [SerialNumber] [nvarchar](30) NOT NULL,
    [ProductNumber] [nvarchar](30) NOT NULL,
    [Purch_Date] [date] NOT NULL,
    [WExpiry_Date] [date] NOT NULL,
    [Memory] [nvarchar](6) NOT NULL,
    [Processor] [nvarchar](10) NOT NULL,
    [HDD] [nvarchar](10) NOT NULL,
    [OS] [nvarchar](25) NOT NULL,
     CONSTRAINT [PK__Workstat__262359ABF6F5A9AA] PRIMARY KEY CLUSTERED 
    (
    [Emp_Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    GO

    MY C# code is , the error appears in  if ((bool)item["Wkst_Status"])

                                                                                  

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



    namespace InventoryStock
    {
        public partial class Workstations : Form
        {
            private IEnumerable<object> query;

            public object WExpiry_Date { get; private set; }

            public Workstations()
            {
                InitializeComponent();
            }

            private void label1_Click(object sender, EventArgs e)
            {

            }

            private void label1_Click_1(object sender, EventArgs e)
            {

            }

            private void Workstations_Load(object sender, EventArgs e)
            {
                // TODO: This line of code loads data into the 'iTInventoryDataSet.Workstations' table. You can move, or remove it, as needed.
                //this.workstationsTableAdapter.Fill(this.iTInventoryDataSet.Workstations);
                comboBox3.SelectedIndex = 0;
            }

            private void button1_Click(object sender, EventArgs e)
            {

                SqlConnection con = new SqlConnection(@"Data Source=sh-jasonk\dev;Initial Catalog=ITInventory;Integrated Security=True");
                //Insert Logic
                con.Open();
                bool Wkst_Status = false;
                if (comboBox3.SelectedIndex == 0)
                {
                    Wkst_Status = true;
                }
                else
                {
                    Wkst_Status = false;
                }

                SqlCommand cmd = new SqlCommand

                (@"INSERT INTO [dbo].[Workstations]
               (
               [Emp_Name]
               ,[Emp_Surname]
               ,[Department]
               ,[Company]
               ,[Hostname]
               ,[Wkst_Status]
               ,[Make]
               ,[Model]
               ,[SerialNumber]
               ,[ProductNumber]
               ,[Purch_Date]
               ,[WExpiry_Date]
               ,[Memory]
               ,[Processor]
               ,[HDD]
               ,[OS])

         VALUES
               ('" + txtName.Text + "','" + txtSurname.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + txtHostName.Text + "','" + comboBox3.SelectedIndex + "','" + txtMake.Text + "','" + txtModel.Text + "','" + txtSN.Text + "','" + txtPN.Text + "','" + dateTimePicker1.Value.ToString("yyyy/MM/dd") + "','" + dateTimePicker1.Value.ToString("yyyy/MM/dd") + "','" + txtMem.Text + "','" + txtProc.Text + "','" + txtHDD.Text + "','" + txtOS.Text + "')",con);


                //Conversion failed here
                cmd.ExecuteNonQuery();
                con.Close();

                //Reading Data
                SqlDataAdapter sda = new SqlDataAdapter(@"Select  [Emp_Name],[Emp_Surname],[Department],[Company],[Hostname],[Wkst_Status],[Make],[Model]
                                                                 ,[SerialNumber],[ProductNumber],[Purch_Date],[WExpiry_Date],[Memory],[Processor],[HDD]
                                                                 ,[OS] From [dbo].[Workstations]", con);

                DataTable dt = new DataTable();
                sda.Fill(dt);
                dataGridView1.Rows.Clear();

                foreach (DataRow item in dt.Rows)
                {
                    int n = dataGridView1.Rows.Add();
                    dataGridView1.Rows[n].Cells[0].Value = item["Emp_Name"].ToString();
                    dataGridView1.Rows[n].Cells[1].Value = item["Emp_Surname"].ToString();
                    dataGridView1.Rows[n].Cells[2].Value = item["Department"].ToString();
                    dataGridView1.Rows[n].Cells[3].Value = item["Company"].ToString();
                    dataGridView1.Rows[n].Cells[4].Value = item["Hostname"].ToString();

                    if ((bool)item["Wkst_Status"])

                    {
                        dataGridView1.Rows[n].Cells[5].Value = "Active";
                    }
                    else
                    {
                        dataGridView1.Rows[n].Cells[5].Value = "Inactive";
                    }

                    dataGridView1.Rows[n].Cells[6].Value = item["Make"].ToString();
                    dataGridView1.Rows[n].Cells[7].Value = item["Model"].ToString();
                    dataGridView1.Rows[n].Cells[8].Value = item["SerialNumber"].ToString();
                    dataGridView1.Rows[n].Cells[9].Value = item["ProductNumber"].ToString();
                    dataGridView1.Rows[n].Cells[10].Value = item["Purch_Date"].ToString();
                    dataGridView1.Rows[n].Cells[11].Value = item["WExpiry_Date"].ToString();
                    dataGridView1.Rows[n].Cells[12].Value = item["Memory"].ToString();
                    dataGridView1.Rows[n].Cells[13].Value = item["Processor"].ToString();
                    dataGridView1.Rows[n].Cells[14].Value = item["HDD"].ToString();
                    dataGridView1.Rows[n].Cells[15].Value = item["OS"].ToString();
                }

            }

            private void label17_Click(object sender, EventArgs e)
            {

            }
        }
    }

    What am i doing wrong and how can i rectify the issue 




    Tuesday, May 21, 2019 6:50 PM

All replies

  • I'm not clear on where the error is raised.  Does it occur on the insert?  You have a comment above cmd.ExecuteNonQuery(); that indicates it is raised there.  Or... is it raised when you are doing the cast to bool on the row from the reader: (bool)item["Wkst_Status"]

    In either case, I have a couple of recommendations:

    1. Store the Wkst_Status as a bit rather than varchar if it is meant to represent a Boolean

    2. Your value for Wkst_Status is derived from the SelectedIndex property of a combobox.  I assume the combobox only has two options in it (true/false) and index 0 = false, etc.  That's OK, but you also need to make sure that a value has been selected, otherwise the SelectedIndex will equal -1 (not castable to bool).

    3. you may want to move the insert statement to a string variable so you can debug it and validate the insert statement is reflecting valid input


    ck

    Tuesday, May 21, 2019 7:26 PM