[c#] How to retrieve data from a SQL Server database in C#?

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?

This question is related to c# sql sql-server

The answer is


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)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

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
          {

          }
   }

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);

    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"]);
                }

 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;

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")


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd