简体   繁体   English

C# 使用 SQL Server 数据填充下拉列表

[英]C# Populating Drop Down with SQL Server data

I am trying to populate a dropdown based on a column in a SQL Server table.我正在尝试根据 SQL Server 表中的列填充下拉列表。 But when I try different get commands, it only shows blank in the dropdown.但是当我尝试不同的 get 命令时,它只在下拉列表中显示空白。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();

            con.ConnectionString = @"Data Source= localhost; Initial Catalog= Travel;Integrated Security=True;";

            con.Open();

            SqlDataReader dr;

            SqlCommand sqlCmd = new SqlCommand("SELECT Sites FROM dbo.Sites", con);
            sqlCmd.CommandType = CommandType.Text;

            dr = sqlCmd.ExecuteReader();

            while (dr.Read())
            {
                comboBox1.Items.Add(dr.GetData(Type));
            }
        }
    }
}

I have looked online at a couple of different methods to get the drop-down to populate but each one triggers a different error.我在网上查看了几种不同的方法来填充下拉列表,但每种方法都会触发不同的错误。 I'm trying to use the least complicated code so that I can understand what is happening in the process.我正在尝试使用最简单的代码,以便我可以了解过程中发生的事情。 I get an error我收到一个错误

'Type' is a type, which is not valid in the given context 'Type' 是一种类型,在给定的上下文中无效

I have searched for this error, but my Google-Fu has failed me.我已经搜索过这个错误,但我的 Google-Fu 失败了。 Any and all help greatly appreciated.任何和所有的帮助都非常感谢。

Change your code to explicitly read the Sites data column:更改您的代码以显式读取Sites数据列:

while (dr.Read())
{
   comboBox1.Items.Add(dr["Sites"]);
} 

On a side note:旁注:

Typically, for larger applications or ones that will need to be maintained into the foreseeable future, you'd want to separate all the DAL (DataAccessLayer) code into a dedicated Manager or Repository.通常,对于较大的应用程序或需要在可预见的未来进行维护的应用程序,您需要将所有 DAL (DataAccessLayer) 代码分离到专用的管理器或存储库中。 Simply create a new project dedicated to accessing the DB, all the methods should return are single instances of domain classes or lists of those.只需创建一个专用于访问数据库的新项目,所有应返回的方法都是域类的单个实例或域类的列表。 Keeping it separate and not having any clue of the Presentation will make your DAL reusable.将它分开并且没有任何关于 Presentation 的线索将使您的 DAL 可重用。 In addition to that, making your Presentation code SQL free will make things more consistent.除此之外,让您的 Presentation 代码 SQL 免费将使事情更加一致。 Then add a project reference to this DAL assembly from your presentation assembly.然后从演示程序集添加对此 DAL 程序集的项目引用。

Thanks again Steve, and you as well T McKeown.再次感谢史蒂夫,还有你和 T McKeown。 I will work on the other suggestions in the comments.我将处理评论中的其他建议。 Here is my revised code so that got the drop-down to work.这是我修改后的代码,这样下拉菜单就可以工作了。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SqlConnection con = new SqlConnection();

            con.ConnectionString = @"Data Source= localhost; Initial Catalog= Travels;Integrated Security=True;";

            con.Open();

            SqlDataReader dr;

            SqlCommand sqlCmd = new SqlCommand("SELECT Sites FROM dbo.Sites", con);
            sqlCmd.CommandType = CommandType.Text;
            dr = sqlCmd.ExecuteReader();
            while (dr.Read())
            {
                comboBox1.Items.Add(dr["Sites"]);
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {


        }
    }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM