Nick
Nick

Reputation: 29

retrieve value from database and assign it in to string variable C#

I want to retrieve value from table. Please guys help me. The thing is I want to get that value and check it with a string value.

this code is not working:

SqlCeCommand cmd1 = new SqlCeCommand("SELECT username FROM tmpusername WHERE _id=1", connection);

SqlCeDataReader usernameRdr = null;

usernameRdr = cmd1.ExecuteReader();

while (usernameRdr.Read()){
    string username11 = usernameRdr["username11"].ToString(); 
}

Upvotes: 0

Views: 53717

Answers (5)

Ranjit Singh
Ranjit Singh

Reputation: 3735

string username11 = (string)usernameRdr["username"];

You have entered wrong column name username11 instead of username.

Upvotes: 0

user1841665
user1841665

Reputation:

You may want to see if dataReader returns any rows first, to prevent null value returns from the database which may cause NullReferenceException so use the following;

string username11=string.empty;

if (usernameRdr.hasRows)
{
while (reader.Read())
{
username11=usernameRdr["username"].ToString();
}
}

Upvotes: 1

Cris
Cris

Reputation: 13351

for handling null values change to,

string username11 = Convert.ToString(usernameRdr["username"]); 

Upvotes: 0

Habib
Habib

Reputation: 223247

use username for accessing column.

string username11 = usernameRdr["username"].ToString(); 

Your select command is specifying Select username and later you are accessing it using username11. That is why you are not getting the value, instead you should be getting an exception.

Upvotes: 2

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

Change it to be :

string username11 = usernameRdr["username"].ToString(); 

The data reader indexer takes the name of the column in the SQL result set which is "SELECT username..." in your SQL query.

Upvotes: 1

Related Questions