0

Well I am not able to figure out the error.No data is coming in variable SqlDataReader.The data retrieved by variable SqlDataReader is stored in Label2.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 }
 protected void Button1_Click(object sender, EventArgs e)
 {
 SqlConnection con = new SqlConnection("Server=(local);Database=records;User Id=sasfddsf;Password=12345");
 try
 {
 con.Open();
 SqlCommand cmd = new SqlCommand("select id,name,referencename from records where name = '" + Label1.Text.ToString() + "'", con);
 var SqlDataReader = cmd.ExecuteReader();
 while (SqlDataReader.Read())
 {
 Label2.Text += Convert.ToString(SqlDataReader["name"]) + Convert.ToString(SqlDataReader["referenceName"]);
 }
 SqlDataReader.Close();
 }
 catch (Exception e1)
 {
 Label2.Text = "Error: " + e1.Message;
 }
 finally 
 {
 con.Close();
 }
 }
}
John Saunders
162k26 gold badges252 silver badges403 bronze badges
asked Jan 29, 2014 at 12:34
3
  • 1
    Does the SQL query return any rows with the given Label1.Text value? Commented Jan 29, 2014 at 12:38
  • 2
    You are inviting people for sql-injection by concatenating your sql-query. Use sql-parameters instead. Commented Jan 29, 2014 at 12:38
  • 1
    And what's the error? Commented Jan 29, 2014 at 12:43

1 Answer 1

1

Try this

 SqlCommand cmd = new SqlCommand("select id,name,referencename from records where name = @TextBoxName", con);
 com.Parameters.AddWithValue("@TextBoxName",Label1.Text.ToString()); 
 SqlDataReader rdr = cmd.ExecuteReader();
 while (rdr.Read())
 {
 Label2.Text += Convert.ToString(rdr["name"]) + Convert.ToString(rdr["referenceName"]);
 }
 rdr.Close();
answered Jan 29, 2014 at 12:40
Sign up to request clarification or add additional context in comments.

4 Comments

I have no idea why this gets upvoted immediately. How is this different?
@TimSchmelter: Parameters make the difference.
@JohnSaunders: there were no parameters in the first version, it was just the same version as OP used with different variable name for the reader. Also, even if using parameters is a good advice it's not clear why this solves the issue.
@TimSchmelter: several reasons why I didn't upvote it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.