Вы вызываете метод GetDataFromDB (строковый запрос) очень часто.Это плохо, потому что вы каждый раз создаете новые SqlConnection и SqlCommand.Это требует времени и ресурсов.Также, если есть какая-либо сетевая задержка, она умножается на количество звонков, которые вы делаете.Так что это просто плохая идея.
Я предлагаю вам вызвать этот метод один раз и заполнить коллекцию, например, словарь, чтобы вы могли быстро найти значение вашего имени пользователя с помощью ключа идентификатора пользователя.
Вот так:
// In the DataField class, have this code.
// This method will query the database for all usernames and user ids and
// return a Dictionary<int, string> where the key is the Id and the value is the
// username. Make this a global variable within the DataField class.
Dictionary<int, string> usernameDict = GetDataFromDB("select id, username from Users");
// Then in the GetValue(int userId) method, do this:
public string GetValue(int userId)
{
// Add some error handling and whatnot.
// And a better name for this method is GetUsername(int userId)
return this.usernameDict[userId];
}
Предложение 2 Вот еще один способ улучшить ситуацию, хотя и немного, в этом случае - использовать класс StringBuilder.Существенный прирост производительности (вот обзор: http://support.microsoft.com/kb/306822).
SringBuilder sb = new StringBuilder();
sb.Append("<table><tr><th>Username</th>");
foreach (DataField f in fields)
{
sb.Append("<th>" + f.Name + "</th>");
}
// Then, when you need the string
string html = sb.ToString();