2011-04-23 179 views
1

我是C#的新手,并试图根据数据库值填充DropDownList。我试图连接到数据库如下所示 - 测试与声明,它说连接。我能否认为这是正确的?我在正确的轨道上吗?另外,我如何从表中选择值并填充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"; 
    } 
} 
+1

香港专业教育学院,现在想通了这一点抱歉浪费任何人的时间:) – Kev 2011-04-23 08:47:22

+1

@Ken:您可以点击** **删除上这个问题,因为你不需要答案,所以它会以低质量结束,没有相关的答案。 – 2011-04-23 09:01:10

+0

由于您将SQL硬编码到您的代码背后,您不妨使用SqlDataSource控件。 http://msdn.microsoft.com/en-us/library/dz12d98w(v=VS.100).aspx – 2011-04-24 14:17:23

回答

2
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 
    { 
      SqlDataReader dReader; 
      SqlCommand cmd = new SqlCommand(); 
      cmd.Connection = connection; 
      cmd.CommandType = CommandType.Text; 
      cmd.CommandText ="Select distinct [Name] from [Names]" + 
      " order by [Name] asc"; 
     connection.Open(); 

     dReader = cmd.ExecuteReader(); 
     if (dReader.HasRows == true) 
     { 
       while (dReader.Read()) 
       //Names collection is a combo box. 
       namesCollection.Add(dReader["Name"].ToString()); 

     } 
     else 
     { 
       MessageBox.Show("Data not found"); 
     } 
      dReader.Close() 
     TextBox1.Text = "connected"; 
    } 
    catch (Exception) 
    { 
     TextBox1.Text = " not connected"; 
    } 
} 

Hope that helps................ 
0

它是如此简单得多:----

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]; 

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