Reputation: 1661
I'm using PostgreSQL DB, and I want to make a data displayer for my friend who doesn't know SQL but sometimes he need to get some information.
I want to write a Windows Forms application which should allow him to type some client id and in result give him some data about this client.
I wrote something like this (below) and I am stuck - after clicking a button I want to pass the answer of my query to a textBox and I can't, tried many solutions. None worked. Anyone can help ?
private void btShowData_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=someServer;Port=1234;User ID=some_user;Password=123456;Database=someDataBase;");
conn.Open();
NpgsqlCommand answer1 = new NpgsqlCommand("SELECT column1 FROM table1 WHERE id = :userId", conn);
answer1.Parameters.Add(new NpgsqlParameter("userId", NpgsqlTypes.NpgsqlDbType.Integer));
answer1.Parameters[0].Value = tbId.Text;
// HERE IS MY PROBLEM - How to pass the answer1 result to the textbox
}
Upvotes: 1
Views: 2523
Reputation: 98770
I'm not too much familiar with PostgresSQL but I think you can use ExecuteScalar
method. It returns first column of the first row as an object
.
If your column1
is character type, you can use it like;
...
answer1.Parameters[0].Value = tbId.Text;
string s = (string)answer1.ExecuteScalar();
TextBox1.Text = s;
Upvotes: 1
Reputation: 560
To pass text to a TextBox all you need to do is write:
TextBoxName.Text = yourVariable.ToString();
Upvotes: -1
Reputation: 26209
Solution 1:
NpgsqlDataReader reader = answer1.ExecuteReader();
if(reader.Read())
{
yourTextBox.Text = reader["column1"].ToString();
}
Solution 2:
yourTextBox.Text = answer1.ExecuteScalar().ToString();
Upvotes: 1