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

  • A+
Category:Languages

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.

 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: