How to add local database items into textBox using

2019-08-02 19:39发布

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!

1条回答
一夜七次
2楼-- · 2019-08-02 20:01

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

}

查看更多
登录 后发表回答