C# 从数据库中填充DropDownList

C# 从数据库中填充DropDownList,c#,asp.net,sql-server,ado.net,drop-down-menu,C#,Asp.net,Sql Server,Ado.net,Drop Down Menu,我是C语言的新手,尝试根据数据库值填充DropDownList。我试着连接到数据库,如下所示——用语句测试,结果显示已连接。我能假定这是正确的吗?我走对了吗?另外,如何从表中选择值并用字段填充DropDownList protected void Page_Load(object sender, EventArgs e) { SqlConnection connection = new SqlConnection ( "Data Source=.\\SQLEXPRESS;Atta

我是C语言的新手,尝试根据数据库值填充DropDownList。我试着连接到数据库,如下所示——用语句测试,结果显示已连接。我能假定这是正确的吗?我走对了吗?另外,如何从表中选择值并用字段填充DropDownList

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection connection = new SqlConnection (
    "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

     try
     {
         connection.Open();
         TextBox1.Text = "connected";
     }
     catch (Exception)
     {
         TextBox1.Text = " not connected";
     }
 }

很简单:--

SqlConnection con = new SqlConnection(); 
DataSet ds = new DataSet(); 
con.ConnectionString = @"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User"; 
SqlCommand cmd = new SqlCommand(query, con); 
cmd.CommandText = query;
con.Open(); 
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];

------------------------------------------------------------------------

我现在明白了这一点,很抱歉浪费了任何人的时间:你在正确的轨道上。要向组合框添加项目,只需comboBox1.items。Addobject@Ken:您可以单击此问题上的“删除”按钮,因为您不需要答案,因此在没有相关答案的情况下,该问题的质量会很低。由于您将SQL硬编码到代码隐藏中,因此您最好使用SqlDataSource控件。
SqlConnection con = new SqlConnection(); 
DataSet ds = new DataSet(); 
con.ConnectionString = @"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User"; 
SqlCommand cmd = new SqlCommand(query, con); 
cmd.CommandText = query;
con.Open(); 
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];

------------------------------------------------------------------------
            using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
            {
                SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
                con.Open();

                dropDownList.DataSource = cmd.ExecuteReader();
                dropDownList.DataTextField = "Name";
                dropDownList.DataValueField = "Name";
                dropDownList.DataBind();
            }