2017-04-12 29 views
1

我想從我的數據庫中加載記錄(性別)到我的窗體窗體,以便它在窗體加載時自動加載,對它有挑戰,因爲它只獲取ID從數據庫而不是性別名稱,我該怎麼做? 下面的代碼片段我如何將記錄載入到窗體FormC s

private void Form1_Load(object sender, EventArgs e) 
{ 
    Load_Gender(); 
} 

public void Load_Gender() 
{ 
    try 
    { 
     string connectionString = @"Data Source=localhost;" + 
     "Initial Catalog=DemoDb;Integrated Security=true; User Instance=False"; 

     SqlConnection connection = new lConnection(connectionString); 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connection; 

     command.CommandText = "SELECT * FROM Gender"; 
     SqlDataAdapter sl = new SqlDataAdapter(command); 

     DataSet ds = new DataSet(); 
     sl.Fill(ds, "Table"); 

     DataTable dt = ds.Tables["Table"]; 

     foreach (DataRow row in dt.Rows) 
     { 
      string id = row["Id"].ToString(); 
      string genderName = row["GenderName"].ToString(); 
     } 

     // Loading RECORDS to comboBox 
     for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
     { 
      comboBoxGender.Items.Add(ds.Tables[0].Rows[i][0].ToString()); 
     } 
    } 
    catch() 
    { 
    } 
} 
+0

需要查看錶DDL才能理解這一點。 –

+0

'行[i] [0]'是包含* Id *的第一列 - 只是更改爲'行[i] [1]'以從第二列獲取* GenderName *。 – Filburt

+0

嘗試使用comboBoxGender.Items.Add(ds.Tables [0] .Rows [i] [1] .ToString()); –

回答

2

編碼它你的foreach循環基本上是什麼都不做,除非你把在調試檢查什麼每一行都包含但你能做到這只是檢查在數據表中定義記憶。

comboBoxGender.Items.Add(ds.Tables[0].Rows[i][0].ToString()); 

此代碼僅抓取Id,因此行[i] [0],0是第一列。

行[i] [1]是性別名稱。

相關問題