Reputation: 37
I have two text boxes in my winform. I would like to enter a userId into first text box, after that by clicking a button display a User Name in the second text box properly. The data is stored in sql server compact. Table name is Users
, and this table contains two columns UserID
and UserName
.
With this code I can open a connection and retrieve the first value from the UserName column,
SqlCeConnection cn = new SqlCeConnection(@"Data Source = D:\Database\Training.sdf");
try
{
cn.Open();
SqlCeCommand cmd = new SqlCeCommand("SELECT UserID, UserName from Users;", cn);
TrainerNameBox.Text = cmd.ExecuteScalar().ToString();
cn.Close();
}
catch
{
}
Upvotes: 1
Views: 934
Reputation: 216363
You are missing the WHERE clause to isolate the username that you want to display
int userID;
if(!Int32.TryParse(txtUserID.Text, out userID))
{
MessageBox.Show("Invalid User ID number");
return;
}
using(SqlCeConnection cn = new SqlCeConnection(@"Data Source = D:\Database\Training.sdf"))
using(SqlCeCommand cmd = new SqlCeCommand("SELECT UserName from Users WHERE UserID=@id;", cn))
{
cn.Open();
cmd.Parameters.AddWithValue("@id", userID);
object result = cmd.ExecuteScalar();
if(result != null)
TrainerNameBox.Text = result.ToString();
else
MessageBox.Show("No user for ID=" + userID.ToString());
}
Notice that ExecuteScalar
returns the first column of the first row, so you need to remove the UserID field from your query and if, the user is not found, you need to check for a null return.
Applying directly the ToString() method to your ExecuteScalar could raise an exception if your user types an invalid id. There is also the problem to validate the user input. If you type a not numeric value for the user id, the conversion will fail. In this case you need to check the input using Int32.TryParse
Upvotes: 1
Reputation: 98868
ExecuteScalar
returns first column of the first row. Other columns or rows are ignored.
In your case, your first column is UserID
. That's why you get first value of this column.
If you want to get UserName
value, you might need to change your query like;
SELECT UserName from Users
And looks like you forget to use WHERE
clause in your query since you want to get UserName
from UserID
. You might need to use using
statement to dispose your SqlCeConnection
and SqlCeCommand
.
Full example;
using(SqlCeConnection cn = new SqlCeConnection(@"Data Source = D:\Database\Training.sdf"))
using(SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "SELECT UserName from Users WHERE UserID = @id";
cmd.Parameters.AddWithValue("@id", (int)txtUserID.Text);
cn.Open();
TrainerNameBox.Text = cmd.ExecuteScalar().ToString();
}
Upvotes: 2
Reputation: 2624
Try this:
Dataset ds = cmd.ExecuteDataset().ToString();
TrainerNameBox.Text = ds.tables[0].Rows[0][1].toString();
TrainerIDBox.Text = ds.tables[0].Rows[0][0].toString();
Upvotes: -1