Visual Studio запрашивает базу данных из переменной DataGridView

#c# #sql #datagridview

#c# #sql #просмотр сетки данных

Вопрос:

Я пытался запросить базу данных access и отобразить результаты в DataDrigView. В таблице отображаются все данные, когда я использую «ВЫБРАТЬ * ИЗ пользовательских платежей». Однако, как только я пытаюсь добавить параметр в запрос, я получаю сообщение об ошибке

 adapter.Fill(ds); //No value given for one more required parameters
 

Однако я уже успешно использовал запрос с использованием параметра в другой части моей программы, кажется, это происходит только тогда, когда я хочу отобразить в таблице данных

 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;

using System.Data.OleDb;
using System.Data.SqlClient; //Import database class


namespace WindowsFormsApplication1
{
    public partial class frmCustomerDetails : Form
    {
        //Database
        //Get connection from database
        String connectionString = staticConnectionString.connectionString;

        //Declare a connection object
        OleDbConnection con;

        //Declare a command object for the SQL
        OleDbCommand cmd;

        //Declare an accedd type reader to read SQL commands
        OleDbDataReader dr;

        String[] CustomerID = new String[500]; 
        String[] CustomerName = new String[500];
        String[] Street = new String[500];
        String[] Area = new String[500];
        String[] PostCode = new String[500];
        String[] TelNo = new String[500];
        String[] Email = new String[500];

        int RecordNo = 0;
        int LastRecord = 0;

        public frmCustomerDetails()
        {
            InitializeComponent();
        }

        private void frmCustomerDetails_Load(object sender, EventArgs e)
        {
            try
            {
                //create a connection object to the database via string location
                con = new OleDbConnection(connectionString);
                //Open the connection to the database
                con.Open();
                //Creat a new command object
                cmd = new OleDbCommand();
                //Set the SQL command text
                cmd.CommandText = "SELECT * FROM Customer WHERE CustomerID = @ID;";

                cmd.Parameters.AddWithValue("@ID", GlobalVar.SelectedCustomer);

                //Link the command to the connection so the correct DB is used
                cmd.Connection = con;
                //Run the command and store resulting table in the datareader
                dr = cmd.ExecuteReader();
            }
            catch (Exception err)
            {
                //Any database errors jump here and output error message
                MessageBox.Show("A database error has occurred: "   Environment.NewLine   err.Message);
            }
            finally
            {
                //Do this whatever happens
                //This is so the first record will be displayed
                //Connection and dr are left open until from closes so more records can be accessed
            }

            //dr.Read() gets the next in the results if possible
            while (dr.Read())
            {
                //Fill the text boxes with data
                CustomerID[RecordNo] = dr["CustomerID"].ToString();
                CustomerName[RecordNo] = dr["Names"].ToString();
                Street[RecordNo] = dr["Street"].ToString();
                Area[RecordNo] = dr["Area"].ToString();
                PostCode[RecordNo] = dr["PostCode"].ToString();
                TelNo[RecordNo] = dr["TelNo"].ToString();
                Email[RecordNo] = dr["Email"].ToString();

                RecordNo = RecordNo   1;

            }
            LastRecord = RecordNo;
            RecordNo = 0;
            ReadDisplay();
        }


        private void btnMenu_Click(object sender, EventArgs e)
        {
            var SelectCustomer = new frmSelectCustomer();
            SelectCustomer.Show();

            this.Close();
        }



        private void btnWeeklyOrders_Click(object sender, EventArgs e)
        {

            String connectionString = staticConnectionString.connectionString;
            OleDbCommand command;
            OleDbDataAdapter adapter;

            con = new OleDbConnection(connectionString);
            command = con.CreateCommand();

            //create data set
            DataSet ds = new DataSet();

            //Clear the gride of data
            CustomerInfo.DataSource = null;

            //create a new dataset
            ds = new DataSet();

            //Open connection
            con.Open();

            //Run the query
            command.CommandText = "SELECT * FROM CustomerPayments WHERE CustomerID = @ID;";
            cmd.Parameters.AddWithValue("@ID", GlobalVar.SelectedCustomer);



            adapter = new OleDbDataAdapter(command);
            adapter.Fill(ds);

            //close connection
            con.Close();

            //Populate grid with data
            CustomerInfo.DataSource = ds.Tables[0];

        }


        private void ReadDisplay()
        {

            lblCustomerID.Text = CustomerID[RecordNo];
            lblNames.Text = CustomerName[RecordNo];
            lblStreet.Text = Street[RecordNo];
            lblArea.Text = Area[RecordNo];
            lblPostCode.Text = PostCode[RecordNo];
            lblTelNo.Text = TelNo[RecordNo];
            lblEmail.Text = Email[RecordNo];

        }

    }
}
 

Комментарии:

1. Какое именно значение GlobalVar.SelectedCustomer ?

2. публичная статическая строка SelectedCustomer; Это переменная, которая хранит идентификатор клиента из другой формы, она работает при отображении данных в табличке, поскольку я успешно использовал ее в этой форме

Ответ №1:

Вы назначаете параметр для неверной OleDbCommand переменной:

 command.CommandText = "SELECT * FROM CustomerPayments WHERE CustomerID = @ID;";
cmd.Parameters.AddWithValue("@ID", GlobalVar.SelectedCustomer);
 

должно быть:

 command.CommandText = "SELECT * FROM CustomerPayments WHERE CustomerID = @ID;";
command.Parameters.AddWithValue("@ID", GlobalVar.SelectedCustomer);
 

Комментарии:

1. аргх, это действительно был долгий день, большое вам спасибо. Это работает