简体   繁体   中英

How to add local database items into textBox using listBox in C#

And i have a question if anyone knows: What would i have to do to add the selected listBox values using the "Firstname" + "Lastname", "Email" and "Address" back into their textboxes?

This code here lets me add my textBox values into database but id like to do the opposite.

private void button_add_Click(object sender, EventArgs e)
{
var insertSQL = "INSERT INTO Inimesed (Firstname, Lastname, Email, Address) VALUES (Firstname, Lastname, Email, Address)";

string connectionString = @"Data Source=myDatabase;Password=xxxxxx;";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
    {
         cn.Open();

        cmd.Parameters.Add("@Firstname", SqlDbType.NVarChar);
        cmd.Parameters.Add("@Lastname", SqlDbType.NVarChar);
        cmd.Parameters.Add("@Email", SqlDbType.NVarChar);
        cmd.Parameters.Add("@Address", SqlDbType.NVarChar);

        cmd.Parameters["Firstname"].Value = textBox1_Firstname.Text;
        cmd.Parameters["Lastname"].Value = textBox2_Lastname.Text;
        cmd.Parameters["Email"].Value = textBox3_Email.Text;
        cmd.Parameters["Address"].Value = textBox4_Address.Text;
        cmd.ExecuteNonQuery();

    }
}

There are tons of tutorials on "How to add textBox items into local database in C#", but none "How to add local database items into textBox". I got all the values defined. Should i use "foreach" commands, "if" commands or "if" commands inside "foreach" commands?

Any help would be great!

How are you going to decide which row you want to retrieve?

Something like the following should retrieve a single row from the database based on email address, then use the values to populate the textboxes:

private void button_retrieve_Click(object sender, EventArgs e)
{
var selectSQL = "select Firstname, Lastname, Email, Address Inimesed where email = @email";

string connectionString = @"Data Source=myDatabase;Password=xxxxxx;";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(selectSQL, cn))
{
     cn.Open();

    cmd.Parameters.Add("@Email", SqlDbType.NVarChar);
    cmd.Parameters["Email"].Value = "emailaddresstofind";

    var rdr = cmd.ExecuteReader();
    try
    {
        if (rdr.Read())
        {
            textBox1_Firstname.Text = rdr.GetString(0);
            textBox2_Lastname.Text = rdr.GetString(1);
            textBox3_Email.Text = rdr.GetString(2);
            textBox4_Address.Text = rdr.GetString(3);
        }
        else
        {
            MessageBox.Show("Could not find record");
        }
    }    
    finally
    {
        rdr.Close();
        cn.Close();
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM