2011-04-23 7 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

필자가 지금 유감이 알아 낸 anyones에 시간 : – Kev

+1

@Ken을 낭비하는 경우 : ** 삭제 클릭 수 **에 이 질문은 답이 필요 없기 때문에 관련 답변없이 낮은 품질로 끝납니다. –

+0

SQL을 코드로 하드 ​​코딩 한 이후로 SqlDataSource 컨트롤을 사용할 수도 있습니다. http://msdn.microsoft.com/en-us/library/dz12d98w(v=VS.100).aspx –

답변

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

------------------------------------------------------------------------ 
관련 문제