【问题标题】:Retrieve Data into Combobox将数据检索到组合框中
【发布时间】:2013-02-19 21:49:11
【问题描述】:

这是我的form 的样子,我的代码是这样的:

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,选择一个,然后文本框会被数据库中的数据填充,这样我就可以删除和更新数据。

【问题讨论】:

  • 您需要在您的代码中实际调用combobox.SelectedItem,您还没有这样做。 另外,将查询直接传递给您的SqlDataAdapter 并不是一个好习惯。了解SqlParameters
  • 我试过循环,但我需要一个变量中的数据计数,然后我可以将项目添加到组合框中
  • 你是个初学者,我只需要一个简单的方法来做事
  • 那么请发布您的所有相关代码。我们 SO 对你是新手、中级还是编码专家不太感兴趣,而对 what you have tried 学习编码更感兴趣:)
  • 我想就是这样,使用该代码我可以插入数据。就这些

标签: c# sql-server combobox textbox


【解决方案1】:

我找到了一个可以使用here的示例。

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()/@ 987654327@。但是这样做仍然是一个好习惯。

提醒您,一旦您对 C# 和 ADO.NET 更加熟悉,我会认真考虑使用 parameterized queries

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多