2014-11-06 38 views
0

我有一個SQL Server數據庫表EmpDetails,它包含兩個行值。我想將這些值保存到另一個表中。但根據我的代碼,我只能得到第一行的值。如何從我的EmpDetails表中獲取所有行值。如何在字符串中設置數據庫表值?

我的示例代碼:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString); 
SqlCommand cmd = new SqlCommand ("select e.MachID,e.Name,e.EmpCode,T.TypeName from EmpDetails e,EmpType t where e.EtypeID=t.EtypeID and e.Deptid='" + dddep.SelectedItem.Value + "'",conn); 
SqlDataAdapter sda = new SqlDataAdapter(cmd); 

DataSet ds = new DataSet(); 
sda.Fill(ds); 

string name = Convert.ToString(ds.Tables[0].Rows[0]["Name"]); 
string code = Convert.ToString(ds.Tables[0].Rows[0]["EmpCode"]); 
string type = Convert.ToString(ds.Tables[0].Rows[0]["TypeName"]); 
+0

通過使用'ds.Tables [0] .Rows [1] [ 「XYZ」]'和存儲那些成不同的變量? – User 2014-11-06 05:51:52

回答

0

你可以做的是重複的行使用的foreach每個表。由於表[0] .Rows返回DataRowCollection,你可以直接把排在一個循環:

var rows = ds.Tables[0].Rows; 
foreach (DataRow row in rows) 
{ 
    var name = row["Name"]; 
    var code= row["EmpCode"]; 
    var type= row["TypeName"]; 
} 

你也可以使用一個集合來存儲值的每一行每一列,也許像列表使用簡單的數據模型。

希望工程!

+0

感謝它的運作 – 2014-11-06 05:59:17

1

你可以嘗試使用一個循環,因爲當你說索引[0]時,你正從第一行獲取值。

實施例:

//let n be the total rows 

for(int i = 0; i < n; i++) 
{ 
    string name = Convert.ToString(ds.Tables[0].Rows[i]["Name"]); 
    string code = Convert.ToString(ds.Tables[0].Rows[i]["EmpCode"]); 
    string type = Convert.ToString(ds.Tables[0].Rows[i]["TypeName"]); 
} 

希望它能幫助

+0

是的這也有幫助 – 2014-11-06 06:02:21

0
if (ds !=null && ds.Tables.count > 0) { 
    foreach (row in ds.Tables["EmpDetails"].Rows) 
    { 
     var name = row["Name"]; 
     var EmpCode= row["EmpCode"]; 
     var TypeName= row["TypeName"]; 
    } 
} 
相關問題