Compare date from textbox with date in database in ASP.NET using C#












0















I am trying to compare a date I enter in a textbox in a DD.MM.YYYY format and I get an error.



string txt = "select count(*) from cont where Data_deschiderii < " + Convert.ToDateTime(TextBox1.Text).ToString("DD.MM.YYYY");

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();

SqlCommand cmd = new SqlCommand(txt, conn);
int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
Response.Write(x);


How could I do it? I couldn't find ANYTHING on the internet










share|improve this question





























    0















    I am trying to compare a date I enter in a textbox in a DD.MM.YYYY format and I get an error.



    string txt = "select count(*) from cont where Data_deschiderii < " + Convert.ToDateTime(TextBox1.Text).ToString("DD.MM.YYYY");

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    conn.Open();

    SqlCommand cmd = new SqlCommand(txt, conn);
    int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
    Response.Write(x);


    How could I do it? I couldn't find ANYTHING on the internet










    share|improve this question



























      0












      0








      0








      I am trying to compare a date I enter in a textbox in a DD.MM.YYYY format and I get an error.



      string txt = "select count(*) from cont where Data_deschiderii < " + Convert.ToDateTime(TextBox1.Text).ToString("DD.MM.YYYY");

      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
      conn.Open();

      SqlCommand cmd = new SqlCommand(txt, conn);
      int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
      Response.Write(x);


      How could I do it? I couldn't find ANYTHING on the internet










      share|improve this question
















      I am trying to compare a date I enter in a textbox in a DD.MM.YYYY format and I get an error.



      string txt = "select count(*) from cont where Data_deschiderii < " + Convert.ToDateTime(TextBox1.Text).ToString("DD.MM.YYYY");

      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
      conn.Open();

      SqlCommand cmd = new SqlCommand(txt, conn);
      int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
      Response.Write(x);


      How could I do it? I couldn't find ANYTHING on the internet







      c# asp.net sql-server date






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 15 '17 at 17:38









      marc_s

      573k12811071255




      573k12811071255










      asked Jan 15 '17 at 17:10









      Ileana ProfeanuIleana Profeanu

      259621




      259621
























          4 Answers
          4






          active

          oldest

          votes


















          3














          The best approach is to start using prepared, parameterized queries. They ensure that comparisons are done correctly, and they prevent the possibility of SQL injection attacks.



          Your code would be rewritten like this:



          string txt = "select count(*) from cont where Data_deschiderii < @compareDate;"; 
          SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
          conn.Open();
          SqlCommand cmd = new SqlCommand(txt, conn);
          cmd.Parameters.Add("@compareDate", SqlDbType.Date);
          cmd.Parameters["@compareDate"].Value = TextBox1.Text;
          int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
          Response.Write(x);


          That is, I am assuming that your database field Data_deschiderii is of a date form of datatype.






          share|improve this answer
























          • thank you, it worked!!!

            – Ileana Profeanu
            Jan 15 '17 at 17:28






          • 2





            Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

            – gmiley
            Jan 15 '17 at 17:30





















          0














          You need to convert the date time to something SQL understands.



          var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");


          And then use formattedDate in your query






          share|improve this answer
























          • it doesn't work, I get an "incorrect syntax near 00" error

            – Ileana Profeanu
            Jan 15 '17 at 17:17











          • It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

            – JonE
            Jan 15 '17 at 17:24



















          0














          You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.






          share|improve this answer































            0














            Try this.



            try
            {
            DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
            DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
            if (Date1 > Date2)
            {
            Your Code...
            }
            }
            catch (Exception ex)
            {
            MessageBox.Show(ex.Message);
            }





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41663895%2fcompare-date-from-textbox-with-date-in-database-in-asp-net-using-c-sharp%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              The best approach is to start using prepared, parameterized queries. They ensure that comparisons are done correctly, and they prevent the possibility of SQL injection attacks.



              Your code would be rewritten like this:



              string txt = "select count(*) from cont where Data_deschiderii < @compareDate;"; 
              SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
              conn.Open();
              SqlCommand cmd = new SqlCommand(txt, conn);
              cmd.Parameters.Add("@compareDate", SqlDbType.Date);
              cmd.Parameters["@compareDate"].Value = TextBox1.Text;
              int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
              Response.Write(x);


              That is, I am assuming that your database field Data_deschiderii is of a date form of datatype.






              share|improve this answer
























              • thank you, it worked!!!

                – Ileana Profeanu
                Jan 15 '17 at 17:28






              • 2





                Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

                – gmiley
                Jan 15 '17 at 17:30


















              3














              The best approach is to start using prepared, parameterized queries. They ensure that comparisons are done correctly, and they prevent the possibility of SQL injection attacks.



              Your code would be rewritten like this:



              string txt = "select count(*) from cont where Data_deschiderii < @compareDate;"; 
              SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
              conn.Open();
              SqlCommand cmd = new SqlCommand(txt, conn);
              cmd.Parameters.Add("@compareDate", SqlDbType.Date);
              cmd.Parameters["@compareDate"].Value = TextBox1.Text;
              int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
              Response.Write(x);


              That is, I am assuming that your database field Data_deschiderii is of a date form of datatype.






              share|improve this answer
























              • thank you, it worked!!!

                – Ileana Profeanu
                Jan 15 '17 at 17:28






              • 2





                Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

                – gmiley
                Jan 15 '17 at 17:30
















              3












              3








              3







              The best approach is to start using prepared, parameterized queries. They ensure that comparisons are done correctly, and they prevent the possibility of SQL injection attacks.



              Your code would be rewritten like this:



              string txt = "select count(*) from cont where Data_deschiderii < @compareDate;"; 
              SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
              conn.Open();
              SqlCommand cmd = new SqlCommand(txt, conn);
              cmd.Parameters.Add("@compareDate", SqlDbType.Date);
              cmd.Parameters["@compareDate"].Value = TextBox1.Text;
              int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
              Response.Write(x);


              That is, I am assuming that your database field Data_deschiderii is of a date form of datatype.






              share|improve this answer













              The best approach is to start using prepared, parameterized queries. They ensure that comparisons are done correctly, and they prevent the possibility of SQL injection attacks.



              Your code would be rewritten like this:



              string txt = "select count(*) from cont where Data_deschiderii < @compareDate;"; 
              SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
              conn.Open();
              SqlCommand cmd = new SqlCommand(txt, conn);
              cmd.Parameters.Add("@compareDate", SqlDbType.Date);
              cmd.Parameters["@compareDate"].Value = TextBox1.Text;
              int x = Convert.ToInt32(cmd.ExecuteScalar().ToString());
              Response.Write(x);


              That is, I am assuming that your database field Data_deschiderii is of a date form of datatype.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jan 15 '17 at 17:19









              gmileygmiley

              5,4601622




              5,4601622













              • thank you, it worked!!!

                – Ileana Profeanu
                Jan 15 '17 at 17:28






              • 2





                Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

                – gmiley
                Jan 15 '17 at 17:30





















              • thank you, it worked!!!

                – Ileana Profeanu
                Jan 15 '17 at 17:28






              • 2





                Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

                – gmiley
                Jan 15 '17 at 17:30



















              thank you, it worked!!!

              – Ileana Profeanu
              Jan 15 '17 at 17:28





              thank you, it worked!!!

              – Ileana Profeanu
              Jan 15 '17 at 17:28




              2




              2





              Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

              – gmiley
              Jan 15 '17 at 17:30







              Sure, keep in mind the use of parameterized queries for all of your SQL commands. Without them you leave yourself open to SQL Injection attacks. By simply using parameterized queries, you get rid of that attack vector all-together. Plus you get the added benefit of ensuring all of your comparisons are properly typed. It also makes the code a lot more readable.

              – gmiley
              Jan 15 '17 at 17:30















              0














              You need to convert the date time to something SQL understands.



              var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");


              And then use formattedDate in your query






              share|improve this answer
























              • it doesn't work, I get an "incorrect syntax near 00" error

                – Ileana Profeanu
                Jan 15 '17 at 17:17











              • It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

                – JonE
                Jan 15 '17 at 17:24
















              0














              You need to convert the date time to something SQL understands.



              var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");


              And then use formattedDate in your query






              share|improve this answer
























              • it doesn't work, I get an "incorrect syntax near 00" error

                – Ileana Profeanu
                Jan 15 '17 at 17:17











              • It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

                – JonE
                Jan 15 '17 at 17:24














              0












              0








              0







              You need to convert the date time to something SQL understands.



              var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");


              And then use formattedDate in your query






              share|improve this answer













              You need to convert the date time to something SQL understands.



              var formattedDate = Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");


              And then use formattedDate in your query







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jan 15 '17 at 17:12









              JonEJonE

              1,78932341




              1,78932341













              • it doesn't work, I get an "incorrect syntax near 00" error

                – Ileana Profeanu
                Jan 15 '17 at 17:17











              • It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

                – JonE
                Jan 15 '17 at 17:24



















              • it doesn't work, I get an "incorrect syntax near 00" error

                – Ileana Profeanu
                Jan 15 '17 at 17:17











              • It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

                – JonE
                Jan 15 '17 at 17:24

















              it doesn't work, I get an "incorrect syntax near 00" error

              – Ileana Profeanu
              Jan 15 '17 at 17:17





              it doesn't work, I get an "incorrect syntax near 00" error

              – Ileana Profeanu
              Jan 15 '17 at 17:17













              It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

              – JonE
              Jan 15 '17 at 17:24





              It's quite possible something else in your query is incorrect. I would check the rest of the query, such as the fields and tables

              – JonE
              Jan 15 '17 at 17:24











              0














              You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.






              share|improve this answer




























                0














                You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.






                share|improve this answer


























                  0












                  0








                  0







                  You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.






                  share|improve this answer













                  You should convert the datetime in timespan and then compare that timespan in seconds. In SQL you could convert the same using DateDiff function.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 15 '17 at 17:15









                  Ankit AgarwalAnkit Agarwal

                  554




                  554























                      0














                      Try this.



                      try
                      {
                      DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
                      DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
                      if (Date1 > Date2)
                      {
                      Your Code...
                      }
                      }
                      catch (Exception ex)
                      {
                      MessageBox.Show(ex.Message);
                      }





                      share|improve this answer






























                        0














                        Try this.



                        try
                        {
                        DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
                        DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
                        if (Date1 > Date2)
                        {
                        Your Code...
                        }
                        }
                        catch (Exception ex)
                        {
                        MessageBox.Show(ex.Message);
                        }





                        share|improve this answer




























                          0












                          0








                          0







                          Try this.



                          try
                          {
                          DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
                          DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
                          if (Date1 > Date2)
                          {
                          Your Code...
                          }
                          }
                          catch (Exception ex)
                          {
                          MessageBox.Show(ex.Message);
                          }





                          share|improve this answer















                          Try this.



                          try
                          {
                          DateTime Date1= Convert.ToDateTime(TextBox1.Text).ToString("yyyy-MM-dd HH:mm:ss");
                          DateTime Date2 = Convert.ToDateTime(TextBox2.Text).ToString("yyyy-MM-dd HH:mm:ss");
                          if (Date1 > Date2)
                          {
                          Your Code...
                          }
                          }
                          catch (Exception ex)
                          {
                          MessageBox.Show(ex.Message);
                          }






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 20 '18 at 8:10

























                          answered Jul 10 '17 at 11:00









                          AlmamunAlmamun

                          12




                          12






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41663895%2fcompare-date-from-textbox-with-date-in-database-in-asp-net-using-c-sharp%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              MongoDB - Not Authorized To Execute Command

                              in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                              How to fix TextFormField cause rebuild widget in Flutter