Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add SQL data to varible

How can I add the SQL data into a variable on c#? Thanks for your help.

 string user = textBox1.Text;
    string password = textBox2.Text;
    con = new SqlConnection("...");//actually, there is a connection string but because of security, I'm not sharing it with you.
    com = new SqlCommand();
    con.Open();
    com.Connection = con;
    com.CommandText = "Select*From login where username='" + textBox1.Text +
        "'And sifre='" + textBox2.Text + "'";
    dr = com.ExecuteReader();
    if (dr.Read())
    {
      
    }

It is my login code it will open a new form but First I should find the username data of it and put it into a varible.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a pattern to follow, place your data operations in a separate class and call in your form. Here Login class could be whatever you want to call it with required properties.

public class Login
{
    public int Id { get; set; }
    . . .
}

Mocked data class, here since select * is used rather than specifying only required columns I assume the first column is the primary key which it may or may not be so adjust as needed and add other columns/properties to the Login class instance.

public class DataOperations
{
    // caller validates parameters have values
    public static Login DoSomething(string userName, string sifre)
    {
        Login login = new Login();

        var selectStatement = "SELECT * FROM login WHERE username= @userName AND sifre = @sifre";

        using (var cn = new SqlConnection("TODO"))
        {
            using (var cmd = new SqlCommand(selectStatement, cn))
            {
                cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = userName;
                cmd.Parameters.Add("@sifre", SqlDbType.NVarChar).Value = sifre;

                cn.Open();

                var reader = cmd.ExecuteReader();

                if (!reader.HasRows) return login;
                reader.Read();
                login.Id = reader.GetInt32(0);
            }
        }

        return login;
    }
}

Call the method above in your form

Login login = DataOperations.DoSomething("TODO", "TODO");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading