Alex
Alex

Reputation: 29

Problem with Getting value from database to my labels Access Database

Hello guys i need to show on my label words from my database and i have a problem, Its not working for me and its not showing the words... I am using Select from And its not showing it...

        string connectionStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\WordssTable.mdb;
    Persist Security Info=False";
    OleDbConnection connectObj = new OleDbConnection(connectionStr);
    connectObj.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connectObj;
    command.CommandText = "SELECT * FROM WordsTable WHERE EnglishWord='" + hebw1.Text + "'";
    command.ExecuteNonQuery();

2

    <form runat="server">
<div id = "Words">
<asp:Label runat="server" id="Engw"></asp:Label>
<br />
<asp:Label id="hebw1" runat="server"></asp:Label>
<asp:Label id="hebw2" runat="server"></asp:Label>
<asp:Label id="hebw3" runat="server"></asp:Label>
<asp:Label id="hebw4" runat="server"></asp:Label>
</div>
</form>

Upvotes: 0

Views: 182

Answers (2)

Steve
Steve

Reputation: 216293

First thing to do is to use the proper using statement around disposable objects. Then change your command text to use parameters placeholders (@text) instead of string concatenations. (This should never be understimated. Parameters prevent parsing errors and sql injection hacks)

Now you are read to request an OleDbDataReader and use it to fill your label with the data coming from the first record retrieved by the OleDbDataReader

string connectionStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\WordssTable.mdb;
Persist Security Info=False";
using(OleDbConnection connectObj = new OleDbConnection(connectionStr))
using(OleDbCommand command = new OleDbCommand())
{
    connectObj.Open();
    command.Connection = connectObj;
    command.CommandText = "SELECT * FROM WordsTable WHERE EnglishWord=@text";
    command.Parameters.Add("@text", OleDbType.VarWChar).Value = hebw1.Text;
    using(OleDbDataReader reader = command.ExecuteReader())
    {
        // Try to read the first record, if any, and then update the labels
        if(reader.Read())
        {
             hebw1.Text = reader["hebw1"].ToString();
             hebw2.Text = reader["hebw2"].ToString();
             hebw3.Text = reader["hebw3"].ToString();
             hebw4.Text = reader["hebw4"].ToString();
        }
   }
}

I assume that your record contains the column hebwX used by the reader indexer and none of this fields is null.

Upvotes: 1

Yuri
Yuri

Reputation: 2900

your ptoblem is that you call command.ExecuteNonQuery() which returns only number of affected rows. You need to change this to

command.CommandText = "SELECT * FROM WordsTable WHERE EnglishWord='" + hebw1.Text + "'";
OleDbReader reader = command.ExecuteReader();
while(reader.Read()){
  // set your label values here
}

Upvotes: 0

Related Questions