如果有人知道,我有一个问题: 我需要做什么才能使用“名字”+“姓氏”,“电子邮件”和“地址”将所选的列表框值添加回其文本框中?
这个代码让我可以将我的textBox值添加到数据库中,但ID却喜欢这样做。
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();
}
}
有很多关于“如何在C#中将textBox项目添加到本地数据库”的教程,但没有“如何将本地数据库项目添加到textBox”。我得到了所有定义的值。 我应该在“foreach”命令中使用“foreach”命令,“if”命令或“if”命令吗?
任何帮助都会很棒!
答案 0 :(得分:2)
您将如何决定要检索哪一行?
以下内容应根据电子邮件地址从数据库中检索单行,然后使用这些值填充文本框:
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();
}
}
}