1

I want to dispaly the data from the datasource based on the type of search the user wants and am not getting any error in the code.. My data grid's name is "Employee_Details", suggest me where am i wrong?

protected void btn_Search_Click(object sender, EventArgs e)
    {
        string search = list_Search.Text;
        string constr = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
        SqlConnection myconnection = new SqlConnection(constr);
        if(string.Compare(search,"Search By Name",true)==0)
        {
            try
            {
                myconnection.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("SELECT * FROM Emp_Details WHERE Name='" + txt_Name.Text + "'", myconnection);
                myReader = myCommand.ExecuteReader();

                SqlDataAdapter da = new SqlDataAdapter(myCommand);
                DataTable dt = new DataTable();

                //da.Fill(dt);
                //DataGrid ds = new DataGrid();
                //Employee_Details.DataSource = dt;

                while (myReader.Read())
                {
                    da.Fill(dt);
                    Employee_Details.DataSource = dt;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                myconnection.Close();
            }
        }


    }
Sarthak
  • 51
  • 3
  • 10

3 Answers3

0

You Forgot to Bind Grid Method.......

       myconnection.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("SELECT * FROM Emp_Details WHERE   

            Name='" + txt_Name.Text + "'", myconnection);
   myReader = myCommand.ExecuteReader(); // it Doesn't Required
   SqlDataAdapter sda = new SqlDataAdapter();
   sda.SelectCommand=myCommand ;
  sda.Fill(dt);
  Employee_Details.DataSource = dt;
  Employee_Details.DataBind();  // You Forgot This thing
Dhaval
  • 2,341
  • 1
  • 13
  • 16
0

Use either SqlDataAdapter or SqlDataReader they both are different approach, Check this. Apart from this you forgor DataBind method.

If you are using SqlDataAdapter change your code like this:-

SqlDataAdapter da= new SqlDataAdapter("SELECT * FROM Emp_Details WHERE Name=@Name, myconnection);
da.SelectCommand.Parameters.Add("@Name",SqlDbType.VarChar).Value = txt_Name.Text; //Change Data Type accordingly
da.Fill(dt);
Employee_Details.DataSource = dt;
Employee_Details.DataBind();

Please remove all the code related to SqlDataReader.

Also, Please use using to dispose your expensive resources. Consider using SqlParameter to stop Sql Injection attacks.

Community
  • 1
  • 1
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
0
            while (myReader.Read())
            {
                da.Fill(dt);
                Employee_Details.DataSource = dt;
               Employee_Details.DataBind();
            }