我正在制作一个学校项目,我需要将文本输入(名称和性别)放入数据库中。然后必须在列表框中显示该数据库(名称和性别)。我现在的代码放在下面,我怎么能让它工作?提前谢谢!
private void Form1_Load(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Persoon", connection))
{
connection.Open();
DataTable PersoonTable = new DataTable();
adapter.Fill(PersoonTable);
lb_gebruikers.DisplayMember = "Naam";
lb_gebruikers.ValueMember = "Id";
lb_gebruikers.DataSource = PersoonTable;
}
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
Persoon nieuwpersoon = new Persoon(naam, geslacht);
personen.Add(nieuwpersoon);
foreach (var Persoon in personen)
{
lb_gebruikers.Items.Add("Naam: " + nieuwpersoon.Naam +
"Geslacht: " + nieuwpersoon.Geslacht);
}
}
答案 0 :(得分:0)
据我所知,你只需要在button1.click和addToList进程之间添加一个插入。
private void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Server =.;Database=People; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand(); // you can define commandText and connection in SqlCommand(defineArea);
cmd.Connection = con; // like; cmd = newSqlCommand("Insert into...",con);
string name = txtName.Text;
string gender = txtGender.Text;
cmd.CommandText = "Insert into Person(Name,Gender)values('" + name + "','" + gender + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
lstBxPerson.Items.Add(name + " - " + gender);
MessageBox.Show("Save Success!");
}
catch (Exception ex)
{
MessageBox.Show("Exception : "+ex);
}
}
数据库名称:人
表名:人