Search code examples
c#sql-server-cesqlexception

C# SqlCeException - a parameter is missing


I have a windows mobile 6 application I am developing. It is accessing a SQL Server CE database and I am receiving the following error:

A Parameter is missing. [Parameter ordinal = 1]

I haven't used SQL Server CE too much but an almost identical application using SQL Server 2008 executed this code with no problems. I can't figure out why it is telling me the parameter is missing!

Here is my code:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;


namespace ElectricBarcodeApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void buttonStart_Click(object sender, EventArgs e)
        {
            System.Data.SqlServerCe.SqlCeConnection conn = new System.Data.SqlServerCe.SqlCeConnection(
            ("Data Source=" + (System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "ElectricReading.sdf") + ";Max Database Size=2047")));
            try
            {
                // Connect to the local database
                conn.Open();
                System.Data.SqlServerCe.SqlCeCommand cmd = conn.CreateCommand();

                SqlCeParameter param = new SqlCeParameter();
                param.ParameterName = "@Barcode";
                param.Value = textBarcode.Text.Trim();

                // Insert a row
                cmd.CommandText = "SELECT Location, Reading FROM Main2 WHERE Barcode LIKE @Barcode";
                cmd.ExecuteNonQuery();

                DataTable data = new DataTable();

                using (SqlCeDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        data.Load(reader);
                    }
                }

                if (data != null)
                {
                    this.dataGrid1.DataSource = data;
                }
            }
            finally
            {
                conn.Close();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (ElectricReadingDataSetUtil.DesignerUtil.IsRunTime())
            {
                // TODO: Delete this line of code to remove the default AutoFill for 'electricReadingDataSet.Main2'.
                this.main2TableAdapter.Fill(this.electricReadingDataSet.Main2);
            }
        }
    }
}

I read some articles saying this error can occur when a decimal is passed because of some msft error but I am not using any data containing decimals. Any help is greatly appreciated!


Solution

  • You should add the parameter to the command, should be something like

    cmd.Parameters.Add(param);