-2

I can't make out what is the mistake. I wanted to retrieve a record from the database table and give them out. There are 9 fields in my table. The data of the second field is the search word. There can be more than one record for the same data. If there are many, then it must show each record at a time. How is it possible to code it?

I use C#.Net for logic and Ms Access for the back end(Database)

This is my code:

string[] arr = new string[9];
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\PassWordSaver\Passwords.mdb;Persist Security Info=True;");
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read();
//while (reader.Read())
//{
    for (int i = 0; i < 9; i++)
    {
       arr[i] = reader.GetValue(i).ToString();
       MessageBox.Show("The New data is " + arr[i] + ".", "Created", MessageBoxButtons.OK);
    }
//}
reader.Close();
MessageBox.Show("Data Added Successfully.  " + arr[2] + " is the user name.", "Created", MessageBoxButtons.OK);
stefan
  • 10,215
  • 4
  • 49
  • 90

3 Answers3

3
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);

Should read:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);

The reason you aren't entering your while loop is that the condition isn't being met to begin with. There is nothing for myReader to read. However, I don't understand why you don't get an error when you run that telling you that you can't convert a textbox control to a string.

  • 1
    Thanks! That was indeed a silly mistake! I never checked for that! Now my code s all well! Thanks A lot! – user2424942 May 27 '13 at 12:53
  • 3
    @user2424942 if the answer solved your problem, you should consider marking this answer as accepted answer to guide the people who suffer from same mistakes. – Cute Bear May 27 '13 at 13:11
0

First of all you're getting into the loop because your query doesn't return any results, and second of all you might want to try and put some parameters on this query like so:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = ?", con);
cmd.Parameters.Add(textBox2.Text); // I assume you mean textBox2.Text
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

May be it will be a silly answer but I think you are trying to send query by taking the value from textbox.Text property. But on the code you are trying to get directly Textbox

OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);

I think you can update as follows

OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);