John Joe

John Joe

  • NA
  • 81
  • 15.9k

I am Trying to Search Record and Display in GridView

Apr 18 2013 5:09 AM
I am trying to search the record and display in GridView  But I am getting an error : Object reference not set to an instance of an object.

How do I solve this?

{
    public partial class Search_Course : System.Web.UI.Page
    {
        public SqlConnection con;
        string constr;
        public void connection()
        {
            constr = ConfigurationManager.ConnectionStrings ["Records"].ToString();
            con = new SqlConnection(constr);
            con.Open();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
        Label1.Visible = false;  
    }
                    private void rep_bind()
                    {
                        connection();
                        string query = "select * from Records where Name like'" + TextBox1.Text  + "%'";
                        SqlDataAdapter da = new SqlDataAdapter(query, con);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        GridView1.DataSource = ds;
                        GridView1.DataBind();
                    }
        protected void Search_Click(object sender, EventArgs e)
        {
            connection();
            string query = "select Name  from Records where Name like'" + TextBox1.Text + "%'";
            SqlCommand com = new SqlCommand(query, con);
            SqlDataReader dr;
            dr = com.ExecuteReader();
            if (dr.HasRows)
            {
                dr.Read();
                rep_bind();
                GridView1.Visible = true;
                TextBox1.Text = "";               
            }
            else
            {
                GridView1.Visible = false;
                Label1.Visible = true;
                Label1.Text = "The search Term " + TextBox1.Text + "  Is Not Available in the Records"; ;
            }
        }
    }
}

Answers (5)