Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the resulting string of a SQL query in C#

I have a table TümEnvanter$ which has 2 columns equipment code (Ekipman) and their description (Tanım).

User chooses the equipment from the combo box, and I want the description of the chosen equipment to appear in the label at the time they choose from combobox.

Here is what I tried:

SqlCommand cmdTanim = new SqlCommand("select Tanım from TümEnvanter$ where Ekipman = '" + comboBox_ekipman.Text + "'", connect);
connect.Open();

SqlDataReader reader = cmdTanim.ExecuteReader();
string tanim = reader.ToString();

labelTanim.Text = "Ekipman Tanımı: "+tanim+" ";

When I use this code, I get in the label:

Ekipman Tanımı: System.Data.SqlClient.SqlDataReader

How can I fix this? Thank you.

like image 305
Beyza S. Avatar asked Dec 24 '22 05:12

Beyza S.


1 Answers

If you only expect a single value, then ExecuteScalar is much simpler than using a reader, i.e.

labelTanim.Text = Convert.ToString(cmdTanim.ExecuteScalar());

In general, perhaps consider tools like "Dapper" which would make this simple even in multi-row cases and solve the SQL injection problem trivially:

string s = connect.QuerySingle<string>(
    "select Tanım from TümEnvanter$ where Ekipman = @val", // command
    new { val = comboBox_ekipman.Text }); // parameters
like image 96
Marc Gravell Avatar answered Dec 25 '22 19:12

Marc Gravell