55

I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:

SqlConnection con = new SqlConnection("Data Source = .;
                                       Initial Catalog = domain;
                                       Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);

I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.

I tried this method but it's not working:

cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";

How can I do it to retrieve all the other values to the textboxes?

Parth Sane
  • 587
  • 7
  • 24
Vivek Dragon
  • 2,218
  • 4
  • 27
  • 48
  • You have `firstname`, `Lastname` and `age`. What is `domainName`? Why `count(*)`? – Hamlet Hakobyan Jan 05 '13 at 12:32
  • Why are you doing a count(*) in your select? And generally you should never do this kind of command text concatenation because you will risk sql injection... Think of a user entering "';drop table tablename;--" – CSharper Jan 05 '13 at 12:33
  • @HamletHakobyan sorry i changed my code for convinence in that i forgot to alter that term – Vivek Dragon Jan 05 '13 at 12:34
  • @CSharper I thought thats the easy way Which i referred from [Here](http://www.dotnetfunda.com/forums/thread9061-how-to-read-values-from-database-for-loginpagewindows-forms.aspx) – Vivek Dragon Jan 05 '13 at 12:37
  • You must get data from DB in any bindable source and bind textboxes to this source. – Hamlet Hakobyan Jan 05 '13 at 12:38
  • @HamletHakobyan yes i tried that but it displays default value of first row. I like to trigger the action using a button – Vivek Dragon Jan 05 '13 at 12:39
  • And how many rows of data you can see in textbox? – Hamlet Hakobyan Jan 05 '13 at 12:41
  • @VivekDragon It's definitely easy... It's just incredibly insecure. When you concatenate strings to form the command text, your user can inject sql code to run in addition to what you have written. – RobH Jan 05 '13 at 12:41
  • did you try to confirm that the query is correct? You can collect it in a string first `string query="Your Query";`, then `MsgBox.show(query);` and confirm that the data is correctly concatenated. – sikas Jan 05 '13 at 12:42
  • 1
    "I tried this method but it's not working" is not at all a helpful description of your problem. – PhoenixReborn Jan 05 '13 at 13:39

6 Answers6

98
 public Person SomeMethod(string fName)
        {
            var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();

            Person matchingPerson = new Person();
            using (SqlConnection myConnection = new SqlConnection(con))
            {
                string oString = "Select * from Employees where FirstName=@fName";
                SqlCommand oCmd = new SqlCommand(oString, myConnection);
                oCmd.Parameters.AddWithValue("@Fname", fName);           
                myConnection.Open();
                using (SqlDataReader oReader = oCmd.ExecuteReader())
                {
                    while (oReader.Read())
                    {    
                        matchingPerson.firstName = oReader["FirstName"].ToString();
                        matchingPerson.lastName = oReader["LastName"].ToString();                       
                    }

                    myConnection.Close();
                }               
            }
            return matchingPerson;
        }

Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.

I've changed this to:

  "Select * from Employees where FirstName=@fName"
  oCmd.Parameters.AddWithValue("@fname", fName);  

So what this block of code is going to do is:

Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided. If that is the case, that person will be stored in a Person object (see below in my answer for the class). If there is no match, the properties of the Person object will be null.

Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you. If you want to be able to store this data, you can add them to a List<Person> .

Person class to make it cleaner:

 public class Person
    {
            public string firstName { get; set; }
            public string lastName { get; set; }
    }

Now to call the method:

Person x = SomeMethod("John");

You can then fill your textboxes with values coming from the Person object like so:

txtLastName.Text = x.LastName;
Parth Sane
  • 587
  • 7
  • 24
Thousand
  • 6,562
  • 3
  • 38
  • 46
  • This is a brilliant answer! – Izzy Nov 12 '14 at 14:55
  • Indeed VERY nice answer. A `try catch` statement is the only thing missing – Vassilis Jun 19 '16 at 13:09
  • 1
    `AddWithValue("@Fname", fName);` `F` should be lower case / upper case in the query – Felix D. Nov 07 '16 at 10:42
  • Shouldn't the parameter name be similar for the Fname and fname? "Notice that the ParameterName property of the SqlParameter instance must be spelled exactly as the parameter that is used in the SqlCommand SQL command string" Reference: https://csharp-station.com/Tutorial/AdoDotNet/Lesson06 – F.A Apr 14 '19 at 18:04
  • 2
    note that using statement will take care of the connection.close. Under the hood, SqlConnection.Dispose() calls the SqlConnection.Close() method, and SqlCommand.Dispose() calls SqlCommand.Close(). – Adil H. Raza Aug 15 '21 at 11:04
3

create a class called DbManager:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);


                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }
  • 1
    Might consider adding an IDisposable on the class and then use the Using for automatic cleanup. e.g. using(DbManager db = new DbManager()) { ... } – Dscoduc Aug 02 '19 at 22:32
2

To retrieve data from database:

 private SqlConnection Conn;

 private void CreateConnection()
 {
    string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
    CreateConnection();

    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";

    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);

    DataTable dt = new DataTable();

    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        throw;
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}
Ashraf Sada
  • 4,527
  • 2
  • 44
  • 48
1

You can use this simple method after setting up your connection:

private void getAgentInfo(string key)//"key" is your search paramter inside database
    {
        con.Open();
        string sqlquery = "SELECT * FROM TableName WHERE firstname = @fName";

        SqlCommand command = new SqlCommand(sqlquery, con); 
        SqlDataReader sReader;

        command.Parameters.Clear();
        command.Parameters.AddWithValue("@fName", key);
        sReader = command.ExecuteReader();

        while (sReader.Read())
        {
            textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
            //["LastName"] the name of your column you want to retrieve from DB

            textBoxAge.Text = sReader["age"].ToString();
            //["age"] another column you want to retrieve
        }
        con.Close();
    }

Now you can pass the key to this method by your textBoxFirstName like:

getAgentInfo(textBoxFirstName.Text);
Vinod Srivastav
  • 3,644
  • 1
  • 27
  • 40
Mahmoud Ayman
  • 1,157
  • 1
  • 17
  • 27
0

we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields

class Db
{
    private readonly static string ConnectionString =
            ConfigurationManager.ConnectionStrings
                        ["DbConnectionString"].ConnectionString;
    public static List<string> GetValuesFromDB(string LocationCode)
    {
        List<string> ValuesFromDB = new List<string>();
        string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
            $"from [CustomerLocations] where LocationCode='{LocationCode}';";
        using (SqlConnection Locationconnection =
                                 new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
            try
            {
                Locationconnection.Open();
                SqlDataReader Locationreader = command.ExecuteReader();
                while (Locationreader.Read())
                {
                    for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
                    {
                        ValuesFromDB.Add(Locationreader[i].ToString());
                    }
                }
                Locationreader.Close();
                return ValuesFromDB;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

    }

}

hope this might helpful

Note: you guys need connection string (in our case "DbConnectionString")

Shrawan
  • 95
  • 2
  • 7
0
    DataTable formerSlidesData = new DataTable();
    DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
                if (formerSlidesData.Rows.Count > 0)
                {
                    DataRow rowa = formerSlidesData.Rows[0];

                    cabinet = Convert.ToInt32(rowa["cabinet"]);
                    box = Convert.ToInt32(rowa["box"]);
                    drawer = Convert.ToInt32(rowa["drawer"]);
                }
Develop4Life
  • 7,581
  • 8
  • 58
  • 76
  • @Zimano not its not. `DataTable` object is being used in below code. Assuming you already have working 1connection` object. – Develop4Life Jun 05 '23 at 18:17