-2

There are four textboxes where user enter values into them and based on the values results gets displayed in gridview.

The problem is When user leaves some textbox the results to be displayed only based on other three textboxes.But my query is not working here. Am facing problem here.

protected void LoadGridData5()
    {
        try
        {
            GridView1.Visible = false;
            con.Open();

            string ID = IDTEXT.Text;
            string ROLE = DropDownList2.SelectedValue.ToString();
            string str = TextBox1.Text.ToString();

            cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
            cmd.Parameters.Add("@NAME", SqlDbType.NVarChar).Value =str;
            cmd.Parameters.Add("@ROLE", SqlDbType.VarChar).Value =ROLE;
            cmd.Parameters.Add("@DOB", SqlDbType.DateTime).Value =DOBTEXT.Text;
            SqlCommand cmd = new SqlCommand("SP_OPERATORS", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "OPERATOR");
            cmd.ExecuteNonQuery();         
            //GridView1.DataSource = ds;
            //GridView1.DataBind();
            //con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                GridView1.DataSource = ds;
                GridView1.DataBind();
                int columncount = GridView1.Rows[0].Cells.Count;
                GridView1.Rows[0].Cells.Clear();
                GridView1.Rows[0].Cells.Add(new TableCell());
                GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
                GridView1.Rows[0].Cells[0].Text = "No Records Found";
            }
        }
        catch
        {
            //Response.Redirect("Error.aspx");
        }
        finally
        {
            con.Close();
        }

    }

Here is the stored procudure

CREATE PROCEDURE SP_OPERATORS
@ID INT,
@NAME NVARCHAR(50),
@DOB DATETIME,
@ROLE VARCHAR(50)

AS
Set NoCount ON

Declare @SQLQuery AS NVarchar(4000)
Declare @ParamDefinition AS NVarchar(2000)

 Set @SQLQuery = 'Select * From [OPERATOR] where (1=1) ' 

 If @NAME Is Not Null 
     Set @SQLQuery = @SQLQuery + ' And (NAME LIKE '''+ '%' + @NAME + '%' + ''')'
 If @ID Is Not Null 
     Set @SQLQuery = @SQLQuery + ' And (ID=@ID)'
 If @DOB Is Not Null 
     Set @SQLQuery = @SQLQuery + ' And (DOB=@DOB)'
 If @ROLE Is Not Null 
     Set @SQLQuery = @SQLQuery + ' And (ROLE=@ROLE)'

      If (@NAME Is Not Null) AND (@DOB Is Not Null )
      Set @SQLQuery = @SQLQuery + ' And (NAME LIKE '''+ '%' + @NAME + '%' + ''')'+'And (DOB=@DOB)'

      If (@NAME Is Not Null) AND (@ROLE Is Not Null )
      Set @SQLQuery = @SQLQuery + ' And (NAME LIKE '''+ '%' + @NAME + '%' + ''')'+' And (ROLE=@ROLE)'

      If (@DOB Is Not Null) AND (@ID Is Not Null )
      Set @SQLQuery = @SQLQuery + ' And (DOB=@DOB)'+' And (ID=@ID)'

      If (@ROLE Is Not Null) AND (@ID Is Not Null )
      Set @SQLQuery = @SQLQuery + '  And (ROLE=@ROLE)'+' And (ID=@ID)'

      If (@ROLE Is Not Null) AND (@DOB Is Not Null )
      Set @SQLQuery = @SQLQuery + '  And (DOB=@DOB)'+' And (ROLE=@ROLE)'

      If (@NAME Is Not Null) AND (@ID Is Not Null ) AND (@ROLE Is Not Null )
      Set @SQLQuery = @SQLQuery + ' And (NAME LIKE '''+ '%' + @NAME + '%' + ''')'+' And (ID=@ID)'+ ' And (ROLE=@ROLE)'

      If (@NAME Is Not Null) AND (@ID Is Not Null ) AND (@DOB Is Not Null )
      Set @SQLQuery = @SQLQuery + ' And (NAME LIKE '''+ '%' + @NAME + '%' + ''')'+' And (ID=@ID)'+ '  And (DOB=@DOB)'

      If (@ROLE Is Not Null) AND (@ID Is Not Null ) AND (@DOB Is Not Null )
      Set @SQLQuery = @SQLQuery + ' And (ROLE=@ROLE)'+' And (ID=@ID)'+ '  And (DOB=@DOB)'

      If (@NAME Is Not Null) AND (@ID Is Not Null ) AND (@DOB Is Not Null ) AND (@ROLE Is Not Null)
      Set @SQLQuery = @SQLQuery + ' And (NAME LIKE '''+ '%' + @NAME + '%' + ''')'+' And (ID=@ID)'+ ' And (ROLE=@ROLE)' + ' And (DOB=@DOB)'

      Set @ParamDefinition =     
       ' @ID INT,
 @NAME NVARCHAR(50),
 @DOB DATETIME,
 @ROLE VARCHAR(50)'

 Execute sp_Executesql     @SQLQuery, 
            @ParamDefinition, 
            @ID, 
            @NAME, 
            @ROLE, 
            @DOB


  If @@ERROR <> 0 GoTo ErrorHandler
   Set NoCount OFF
   Return(0)

  ErrorHandler:
  Return(@@ERROR)
  GO
  • That query will obviously fail, just run that on SSMS directly with sample values plus your code is open for `SQL Injection attach`. Better to do this in a SP. Refer some sample search SP. – Rahul Singh Aug 17 '15 at 11:21
  • NB: You're using `ExecuteNonQuery` to execute a query. See http://stackoverflow.com/questions/21058970/when-to-use-executescalar-executereader-executenonquery – JohnLBevan Aug 17 '15 at 11:33

1 Answers1

0

Your call to da.Fill(ds) will execute the query, no need for the extra cmd.ExecuteNonQuery after it.

For your own sake, please please please either switch the constructed string you're using for the query to either a call to a stored procedure, or to a parameterised query. You're open to SQL Injection if someone puts a malicious value in any of those text boxes. There are more details on this here (http://www.techrepublic.com/article/shorten-development-time-by-using-parameterized-queries-in-adonet/) and here (https://msdn.microsoft.com/en-us/library/bbw6zyha(v=vs.110).aspx)

It's also not terribly clear what you're trying to do with the query. At the moment it's going to try and match all of the parameters that you specify, as you're using 'AND' between each predicate. If you're trying to do a search, you may want some of those to be 'ORs' or you may want to only add the predicates where the value is supplied. At the moment, for example, if you leave your ID textbox blank, you'll only return results where the ID of the OPERATOR is blank, and that doesn't sound like your intention.

Chris Disley
  • 1,286
  • 17
  • 30
  • Yes,If I leave a textbox empty,what should be the query so that I retrieve values not considering the empty textbox. Leaving a textbox is like considering all possibities of that attribute. – HARIKRISHNA PARIVEDA Aug 17 '15 at 12:24
  • That's what I mean. So if you have that ID="'+ID+"' part in the query, it's still going to be checked when your value is blank. You need to construct the SQL query based on whether or not you've specified values for those textboxes, so if you haven't supplied an ID, you shouldn't add a predicate for ID= to the query. Although procedures like this are often frowned upon because of their performance issues, you can use a pattern like the one specified here (http://stackoverflow.com/a/3415629/939080) within a stored procedure to only use values when you specify a particular param. – Chris Disley Aug 17 '15 at 12:28
  • Like you Said I have created a stored Procedure and tried to run but it doesn't work as expected. – HARIKRISHNA PARIVEDA Aug 18 '15 at 09:34
  • If you update your original post with the query you're using in the stored procedure and the code you're using to call it, we may be able to work out what's wrong. – Chris Disley Aug 18 '15 at 09:38
  • Updated.Please have a look – HARIKRISHNA PARIVEDA Aug 18 '15 at 09:41
  • OK, well in this instance, it's pretty clear. You're still always passing something into the stored procedure parameters, even when the fields are blank. If you change the lines that follow the pattern cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID; to only call those lines where the textbox value isn't empty (!string.IsNullOrEmpty(textbox.Value)), that will give you the expected result. – Chris Disley Aug 18 '15 at 10:44