1

I've 2 ComboBox controls on my Windows Form named comboBox1 and comboBox2. Items in comboBox1 are loaded from database at form's load event and I'm trying to add items to comboBox2 when the user selects an item from the comboBox1 and getting this error.

Procedure or function 'SubjectCodeQuery' expects parameter '@StudentId', which was not supplied.

Here's my code:

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

namespace StudentAttendanceSystem
{
    public partial class AttendanceEntry : Form
    {
        private string sasdbConnectionString = @"Data Source=(LocalDB)\v11.0;Initial Catalog=sasdb;Integrated Security=True;Pooling=False";
        public AttendanceEntry()
        {
            InitializeComponent();
        }

        private void AttendanceEntry_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(sasdbConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT StudentId FROM Students", conn);

            cmd.CommandType = CommandType.Text;

            conn.Open();

            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                this.comboBox1.Items.Add(dr.GetInt32(0).ToString());
            }

            dr.Close();

            conn.Close();

            toolStripStatusLabel1.Text = "";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(sasdbConnectionString);
            SqlCommand cmd = new SqlCommand("SubjectCodeQuery", conn);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@StudentId", comboBox1.SelectedValue);

            conn.Open();

            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                this.comboBox2.Items.Add(dr.GetInt32(0).ToString());
            }

            conn.Close();
        }
    }
}
Shyam Singh
  • 123
  • 2
  • 14
  • 3
    Try using SelectedItem instead of SelectedValue since it doesn't look like you have set the ValueMember property. – LarsTech Mar 19 '14 at 13:48
  • Additionally you should be using a [Using Statement](http://stackoverflow.com/questions/10057334/when-should-i-use-the-using-statement) for your SqlConnections, as well as your SqlDataReader. – Amicable Mar 19 '14 at 13:52
  • Thanks, I'll include that. – Shyam Singh Mar 19 '14 at 14:00

0 Answers0