How to Display data in textbox using MS Access database

fkr picture fkr · Mar 24, 2014 · Viewed 8.7k times · Source

Im trying to display user data from database into textbox, so that user can edit/update that data later.

Im getting error of no value has been set for at least one of the required parameters.

I did not write the SELECT * FROM, because i'm not displaying data like AdminRights.

Can you please help me fix the error?

This is my code

private void refresh_Click(object sender, RoutedEventArgs e)
    {
        if (!isPostBack)
        {
            DataTable dt = new DataTable();
            con.Open();
            OleDbDataReader dr = null;
            OleDbCommand cmd = new OleDbCommand("SELECT [Name], [LastName], [UserName], [Password], [Address], [Email] FROM User WHERE [ID] = ?", con);
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                name.Text = (dr["Name"].ToString());
                lName.Text = (dr["LastName"].ToString());
                uName.Text = (dr["UserName"].ToString());
                pass.Text = (dr["Password"].ToString());
                address.Text = (dr["Address"].ToString());  
                email.Text = (dr["Email"].ToString());
                id.Text = (dr["ID"].ToString());
            }
            con.Close();
        }
    }

Answer

Steve picture Steve · Mar 24, 2014
.....FROM User WHERE [ID] = ?", con);

The ? placeholder requires a parameter defined in the command parameters collection.

So, before calling ExecuteReader you need to add the parameter for the ID field

 cmd.Parameters.AddWithValue("@p1", ????value for the ID field);
 dr = cmd.ExecuteReader();

If you want to retrieve a single record from your table you need to know the value for the field that uniquely identifies the records in your table.
To get that value it is necessary to understand how do you reach this code. If you select a row from a list, grid or combo, probably you have loaded that control with your user names and their ID.