如何在for循环中访问字段值的列名。
我不想对列名进行硬编码。
DataAccessObject NewDao = Settings.IntranetDBDataAccessObject;
string UserName = "";
string WorkPhone = "";
string ColumnName = "";
if (Request.QueryString["user_id"] != null && Request.QueryString["user_id"].Length != 0) {
SqlCommand Select = new SqlCommand("SELECT emp_name, phone_work FROM employees WHERE emp_id="+
NewDao.ToSql(Request.QueryString["user_id"].ToString(),FieldType.Integer),NewDao);
DataRowCollection newDr = Select.Execute().Tables[0].Rows;
for(int i = 0; i < newDr.Count; i++) {
UserName = newDr[i]["emp_name"].ToString();
WorkPhone = newDr[i]["phone_work"].ToString();
//Is there a way to access the Key column that contains data row field value?
//ColumnName = newDr[i][ ?columnNameFromSelect? ].ToString();
}
// Show a label value
UserInfo.Text = UserName + ", phone: "+WorkPhone;
}
答案 0 :(得分:1)
您应该使用DataTable
的{{1}}属性:
Columns
答案 1 :(得分:0)
您也可以从datareader获取查询中的架构:
SqlDataReader reader = command.ExecuteReader();
DataTable schemaTable = reader.GetSchemaTable();
根据msdn的文档: https://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx 关于从DataReader获取架构信息的部分