2011-04-23 180 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]; 

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