Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在字符串中设置数据库表值?_C#_Sql_Sql Server - Fatal编程技术网

C# 如何在字符串中设置数据库表值?

C# 如何在字符串中设置数据库表值?,c#,sql,sql-server,C#,Sql,Sql Server,我有一个SQL Server数据库表EmpDetails,它包含两行值。我想将这些值保存到另一个表中。但根据我的代码,我只能得到第一行的值。如何从我的EmpDetails表中获取所有行值 我的示例代码是: SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString); SqlCommand cmd = new SqlCo

我有一个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"]);

您可以使用foreach迭代每个表中的行。由于表[0]。行返回DataRowCollection,因此可以直接将行放入循环中:

var rows = ds.Tables[0].Rows;
foreach (DataRow row in rows)
{
   var name = row["Name"];
   var code= row["EmpCode"];
   var type= row["TypeName"];
}
您可以使用集合来存储每行中每列的值,就像使用简单数据模型的列表一样


希望能成功

您可以尝试使用循环,因为当您说index[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"]);
}
//设n为总行数
对于(int i=0;i

希望通过使用
ds.Tables[0].Rows[1][“XYZ”]
并将它们存储到不同的变量中来帮助您

?是的,这也很有帮助
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"];
    }
}