This question already has answers here:
Can you get the column names from a SqlDataReader?
                                
                                    (9个答案)
                                
                        
                                5年前关闭。
            
                    
我有以下代码:

string result = null;
        string query = "SELECT * FROM Energy";
        int index = 0;

        sql.ConnOpen();

        cmd = sql.Command(query);

        try
        {
            reader = cmd.ExecuteReader();

            while (reader.Read())
            {

                result += "Date: " + reader["Date"].ToString() + "Here goes columnName " +  (reader[index++].ToString().Equals("0") ? "No" : "Yes") + "\n";
            }
        }


它说:Here goes columnName(在while循环中),我想添加当前列的名称。
我该如何获得?因此请注意,我需要当前列的名称,而不是当前列的值

最佳答案

SqlDataReader有一个GetName方法,该方法获取列索引并返回列名称。当传递列名时,GetOrdinal方法以相反的方式返回列索引。

10-08 16:31