Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. how to check if value exists in database from textbox c#

how to check if value exists in database from textbox c#

Scheduled Pinned Locked Moved C#
csharpdatabasetutorial
14 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Member_14644251

    its hard

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #3

    It's easy:

    commandText = "SELECT user from UserTable where id = @username"
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@username", tbUser.Text);

    1 Reply Last reply
    0
    • M Member_14644251

      its hard

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #4

      It's not hard, it's easy - once you learn how to do it. Just to add to what Richard gave you, the whole code is along the lines of:

              using (SqlConnection con = new SqlConnection(strConnect))
                  {
                  con.Open();
                  using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
                      {
                      cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
                      using (SqlDataReader reader = cmd.ExecuteReader())
                          {
                          while (reader.Read())
                              {
                              int age = (int) reader\["Age"\];
                              string desc = (string) reader\["Description"\];
                              Console.WriteLine($"{age}\\n{desc}");
                              }
                          }
                      }
                  }
      

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      1 Reply Last reply
      0
      • M Member_14644251

        its hard

        realJSOPR Offline
        realJSOPR Offline
        realJSOP
        wrote on last edited by
        #5

        Answering a question like this is harder.

        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
        -----
        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
        -----
        When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

        1 Reply Last reply
        0
        • M Member_14644251

          its hard

          H Offline
          H Offline
          Hailu Worku Obsse
          wrote on last edited by
          #6

          Step one: Add new LINQ to SQL item from project Item in to your project and call it DXD (or any convinient name you like) Step two: drag and Drop the Employee TABLE from Server Explorer in your IDE to your LINQ to SQL DataContext object. Step Three: Add data source by selecting Object as data source Step Four: Go to your form and drag and drop Salary field from your data source object to your form Step Five: Set the Data Source of your EmployeeDatabinding object as EmployeeDatabinding.DataSource = DXD.Employee ... it is too long try another approach

          P 1 Reply Last reply
          0
          • H Hailu Worku Obsse

            Step one: Add new LINQ to SQL item from project Item in to your project and call it DXD (or any convinient name you like) Step two: drag and Drop the Employee TABLE from Server Explorer in your IDE to your LINQ to SQL DataContext object. Step Three: Add data source by selecting Object as data source Step Four: Go to your form and drag and drop Salary field from your data source object to your form Step Five: Set the Data Source of your EmployeeDatabinding object as EmployeeDatabinding.DataSource = DXD.Employee ... it is too long try another approach

            P Offline
            P Offline
            Pete OHanlon
            wrote on last edited by
            #7

            And what happens if the database is not SQL Server? What if the textbox is an ASP.NET Core one? You are making a lot of assumptions with your answer.

            Advanced TypeScript Programming Projects

            L 1 Reply Last reply
            0
            • P Pete OHanlon

              As you haven't provided any real detail, the most detailed answer I can give is that you'll need to do a SELECT using your value.

              Advanced TypeScript Programming Projects

              F Offline
              F Offline
              F ES Sitecore
              wrote on last edited by
              #8

              "SELECT"? He didn't say it was a SQL based database. You're making a lot of assumptions here ;)

              P 1 Reply Last reply
              0
              • P Pete OHanlon

                And what happens if the database is not SQL Server? What if the textbox is an ASP.NET Core one? You are making a lot of assumptions with your answer.

                Advanced TypeScript Programming Projects

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #9

                Pete O'Hanlon wrote:

                And what happens if the database is not SQL Server? What if the textbox is an ASP.NET Core one? You are making a lot of assumptions with your answer.

                Same can be said from OG's answer, which I still find very valuable. The assumption for SQL Server is a valid one; if it is another database a similar technique is used and the example given remains valid with minimal change. I'd argue that it should program against the interface, and use the CreateCommand method from the connection, taking the value of the textbox as an argument.

                using (SqlConnection con = new SqlConnection(strConnect))
                using (IDbCommand cmd = con.CreateCommand())
                {
                cmd.CommandText = "bla";
                con.Open(); // as late as possible

                And yes, even that would be improved by using the DBProviderFactory, getting the connectionstring and provider from the Settings.

                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^] "If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.

                1 Reply Last reply
                0
                • F F ES Sitecore

                  "SELECT"? He didn't say it was a SQL based database. You're making a lot of assumptions here ;)

                  P Offline
                  P Offline
                  Pete OHanlon
                  wrote on last edited by
                  #10

                  This is true. It could be a find for all I know. Well spotted.

                  Advanced TypeScript Programming Projects

                  1 Reply Last reply
                  0
                  • M Member_14644251

                    its hard

                    realJSOPR Offline
                    realJSOPR Offline
                    realJSOP
                    wrote on last edited by
                    #11

                    There are as many ways to do this as there are people answering this question. Most of them depend on what mechanism you're using to access your database - Entity Framework - ADO - LINQ to SQL, or whatever. I personally prefer ADO, and I've written a reasonably generic DAL object to do it. Generic DAL using ADO[^] It can process stored proc calls or straight-up queries, and can map the returned data set to any object. Beyond that, your question is so vague that there's nothing more I can suggest

                    ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                    -----
                    You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                    -----
                    When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                    1 Reply Last reply
                    0
                    • M Member_14644251

                      its hard

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #12

                      How big is the "database" (table)? Sometimes, it's simply more efficient to load the entire table into memory and reference it (i.e. for "look-ups") during data entry. No fancy querying required.

                      It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

                      1 Reply Last reply
                      0
                      • M Member_14644251

                        its hard

                        S Offline
                        S Offline
                        Shraddha_Patel
                        wrote on last edited by
                        #13

                        private void CheckContactNumber() { string checkContactNum = "SELECT COUNT(*) FROM Employee WHERE ContactNumber = " + addContactNum.Text + " "; //01234567890 OleDbCommand cmd = new OleDbCommand(checkContactNum, conn); conn.Open(); OleDbDataReader dr = cmd.ExecuteReader(); //if (dr.Read() && addContactNum.Text != "") if (dr.Read()) { int count = (int)dr[0]; if(count>0) { err += "Contact number is already listed in the database\r\n"; errorContactNum.Visible = true; uniqueContactNumber = false; } } conn.Close(); }

                        1 Reply Last reply
                        0
                        • M Member_14644251

                          its hard

                          R Offline
                          R Offline
                          Roland Skeyhill
                          wrote on last edited by
                          #14

                          t's not hard, it's easy - once you learn how to do it. Just to add to what Richard gave you, the whole code is along the lines of:

                          using (SqlConnection con = new SqlConnection(strConnect))
                          {
                          con.Open();
                          using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
                          {
                          cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
                          using (SqlDataReader reader = cmd.ExecuteReader())
                          {
                          while (reader.Read())
                          {
                          int age = (int) reader["Age"];
                          string desc = (string) reader["Description"];
                          Console.WriteLine($"{age}\n{desc}");
                          }
                          }
                          }
                          }

                          :laugh: :cool:

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups