将数据检索到组合框中

本文关键字:组合 数据 检索 | 更新日期: 2023-09-27 18:00:06

这就是我的表单,我的代码是这样的:

using System.Data.SqlClient;
namespace ProjectCSharpSQLserver
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection(@"Data Source=.'SQLEXPRESS;AttachDbFilename=I:'ProjectCSharpSQLserver'ProjectCSharpSQLserver'CsSQL.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();
        DataTable dt = new DataTable();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            cn.Open();
            SqlDataAdapter sda = new SqlDataAdapter("insert into info (id, Name, phone, Address) Values ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "')", cn);
            sda.Fill(dt);
            cn.Close();
        }
    }
}

我需要知道如何打开组合框,找到Id,选择一个,然后用数据库中的数据填充文本框,这样我就可以删除和更新数据。

将数据检索到组合框中

我发现了一个可以在这里使用的示例。

private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
   ComboBox cb = (ComboBox)sender;
   cn.Open();
   SqlDataAdapter sda = new SqlDataAdapter("Place your DELETE statement here", cn);
   sda.Fill(dt);
   cn.Close();
}

这将在每次更改combobox中的选定语句时运行该语句。顺便说一句,当您运行SqlDataAdapter时,它将自动为您打开和关闭与数据库的连接,这样您就不必使用cn.Open()/cn.Close()。但这样做仍然是一个好习惯

只是为了提醒您,一旦您对C#和ADO.NET更加熟悉,我会认真研究使用参数化查询。