patterncsharpMinor
Comparing database values with values from a GridView
Viewed 0 times
gridviewcomparingwithdatabasevaluesfrom
Problem
I have a block of C# code here that stores data to an
Is there a way to reduce the line of code and improve its readability?
ArrayList from the database and compares each with the values from the GridView.Is there a way to reduce the line of code and improve its readability?
while (DataReader.Read())
{
arrHostName.Add(DataReader.GetString(0));
arrUsers.Add(DataReader.GetString(2));
arrPSName.Add(DataReader.GetString(3));
}
foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)
{
string rowHostName = row.Cells["HostName"].Value.ToString();
string rowUsers = row.Cells["Users"].Value.ToString();
string rowPSName= row.Cells["PS_NAME"].Value.ToString();
foreach (string a in arrHostName)
{
if (rowHostName == a.ToString())
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}
}
foreach (string a in arrUsers)
{
if (rowUsers == a.ToString())
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}
}
foreach (string a in arrPSName)
{
if (rowPSName == a.ToString())
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}
}
}Solution
It looks like what you want is
And if you only use the collections above to check if they contain some values, you should prefer
Of course, you should then change the names of the local variables accordingly, from
ArrayList.Contains.string rowHostName = row.Cells["HostName"].Value.ToString();
string rowUsers = row.Cells["Users"].Value.ToString();
string rowPSName= row.Cells["PS_NAME"].Value.ToString();
if (arrHostName.Contains(rowHostName)
|| arrUsers.Contains(rowUsers)
|| arrPSName.Contains(rowPSName))
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}And if you only use the collections above to check if they contain some values, you should prefer
HashSet over ArrayList.Of course, you should then change the names of the local variables accordingly, from
arrHostName to hostNames and so on. It is always better not to clutter variable names with type information in C#, whose type system is good enough.Code Snippets
string rowHostName = row.Cells["HostName"].Value.ToString();
string rowUsers = row.Cells["Users"].Value.ToString();
string rowPSName= row.Cells["PS_NAME"].Value.ToString();
if (arrHostName.Contains(rowHostName)
|| arrUsers.Contains(rowUsers)
|| arrPSName.Contains(rowPSName))
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}Context
StackExchange Code Review Q#27074, answer score: 8
Revisions (0)
No revisions yet.