Am trying to read product name from the sql database and iwant to display it using amessage box on the form.but when i debug,the message box is empty.where is the problem.
//code to read name from the database.
public string hardname()
{
string name = "";
try
{
SqlConnection con = new SqlConnection("Data Source=HISHAMKAL-PC;Initial Catalog=LA GHardware;User ID=sa;Password=hish;");
SqlCommand cmd = new SqlCommand("SELECT 'Product_Name' FROM Hardware WHERE ID=" + textBox1.Text,con);
SqlDataReader reder = cmd.ExecuteReader();
while (reder.Read())
{
name =(string)reder[0];
}
con.Close();
}
catch(Exception x)
{
x.ToString();
}
return name;
}
//code behind the button
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(hardname());
}
C# asp.net winforms strings
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.

VulpesRank #55 · 29.2K reputationPosted Dec 15, 2013, 6:05 AM EST
SqlCommand cmd = new SqlCommand("SELECT 'Product_Name' FROM Hardware WHERE ID=" + textBox1.Text,con);
to this:
SqlCommand cmd = new SqlCommand("SELECT Product_Name FROM Hardware WHERE ID=" + textBox1.Text,con); // now no quotes around Product_Name
Abhay ShankerRank #375 · 6.7K reputationPosted Dec 15, 2013, 5:08 PM EST
1. Replace cmd with "SELECT Product_Name FROM Hardware WHERE ID=" + textBox1.Text,con
2. name = reader.GetString(0); --> Whatever is the index