Question

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();
        }
    }
}
Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top