Loading information from a SQL DB to an array of buttons, they are not in order [closed]

I am writing a point-of-sale (POS) app where I have the layout number (1-35), text (price and product name) and image of the buttons in a SQL database. There is a ItemLayout table in the database, that includes the item ID (PLU), the layout number (1-35), if the button should be visible in the first place (all working) and the group of the item. They are read with the following function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public ILMButtonsProps[] getILMButtonProps(string GroupName)
{
ILMButtonsProps[] result = new ILMButtonsProps[getILMAmount(GroupName)];
try
{
SqlConnection con = new SqlConnection(returnConString());
con.Open();
string operation = "SELECT * FROM ItemLayout WHERE ItemGroup=@ItemGroup";
SqlCommand cmd = new SqlCommand(operation, con);
cmd.Parameters.AddWithValue("@ItemGroup", GroupName);
SqlDataReader reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
result[count] = new ILMButtonsProps();
result[count].ItemGroup = reader["ItemGroup"].ToString();
result[count].LayoutNumber = reader["Number"].ToString();
result[count].Enable = Convert.ToInt32(reader["Enable"].ToString());
result[count].PLU = reader["PLU"].ToString();
count++;
}
reader.Close();
con.Close();
}
catch (Exception ex)
{
helperClass.throwError(ex.Message, ex.Source);
}
return result;
}
</code>
<code>public ILMButtonsProps[] getILMButtonProps(string GroupName) { ILMButtonsProps[] result = new ILMButtonsProps[getILMAmount(GroupName)]; try { SqlConnection con = new SqlConnection(returnConString()); con.Open(); string operation = "SELECT * FROM ItemLayout WHERE ItemGroup=@ItemGroup"; SqlCommand cmd = new SqlCommand(operation, con); cmd.Parameters.AddWithValue("@ItemGroup", GroupName); SqlDataReader reader = cmd.ExecuteReader(); int count = 0; while (reader.Read()) { result[count] = new ILMButtonsProps(); result[count].ItemGroup = reader["ItemGroup"].ToString(); result[count].LayoutNumber = reader["Number"].ToString(); result[count].Enable = Convert.ToInt32(reader["Enable"].ToString()); result[count].PLU = reader["PLU"].ToString(); count++; } reader.Close(); con.Close(); } catch (Exception ex) { helperClass.throwError(ex.Message, ex.Source); } return result; } </code>
public ILMButtonsProps[] getILMButtonProps(string GroupName)
{
    ILMButtonsProps[] result = new ILMButtonsProps[getILMAmount(GroupName)];
    try
    {
        SqlConnection con = new SqlConnection(returnConString());
        con.Open();

        string operation = "SELECT * FROM ItemLayout WHERE ItemGroup=@ItemGroup";
        SqlCommand cmd = new SqlCommand(operation, con);
        cmd.Parameters.AddWithValue("@ItemGroup", GroupName);
        SqlDataReader reader = cmd.ExecuteReader();

        int count = 0;
        while (reader.Read())
        {
            result[count] = new ILMButtonsProps();
            result[count].ItemGroup = reader["ItemGroup"].ToString();
            result[count].LayoutNumber = reader["Number"].ToString();
            result[count].Enable = Convert.ToInt32(reader["Enable"].ToString());
            result[count].PLU = reader["PLU"].ToString();

            count++;
        }
        reader.Close();
        con.Close();

    }
    catch (Exception ex)
    {
        helperClass.throwError(ex.Message, ex.Source);
    }
    return result;
}

The function used to get the length for the array:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public int getILMAmount(string GroupName)
{
int result = 0;
try
{
SqlConnection con = new SqlConnection(returnConString());
con.Open();
string operation = "SELECT * FROM ItemLayout WHERE ItemGroup=@GroupName";
SqlCommand cmd = new SqlCommand(operation, con);
cmd.Parameters.AddWithValue("@GroupName", GroupName);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result++;
}
reader.Close();
con.Close();
}
catch (Exception ex)
{
helperClass.throwError(ex.Message, ex.Source);
}
return result;
}
</code>
<code>public int getILMAmount(string GroupName) { int result = 0; try { SqlConnection con = new SqlConnection(returnConString()); con.Open(); string operation = "SELECT * FROM ItemLayout WHERE ItemGroup=@GroupName"; SqlCommand cmd = new SqlCommand(operation, con); cmd.Parameters.AddWithValue("@GroupName", GroupName); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { result++; } reader.Close(); con.Close(); } catch (Exception ex) { helperClass.throwError(ex.Message, ex.Source); } return result; } </code>
public int getILMAmount(string GroupName)
{
    int result = 0;
    try
    {
        SqlConnection con = new SqlConnection(returnConString());
        con.Open();

        string operation = "SELECT * FROM ItemLayout WHERE ItemGroup=@GroupName";
        SqlCommand cmd = new SqlCommand(operation, con);
        cmd.Parameters.AddWithValue("@GroupName", GroupName);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            result++;
        }
        reader.Close();
        con.Close();

    }
    catch (Exception ex)
    {
        helperClass.throwError(ex.Message, ex.Source);
    }
    return result;
}

And the class used (I don’t think this is very important here but anyways:)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>internal class ILMButtonsProps
{
internal string ItemGroup;
internal string LayoutNumber;
internal int Enable;
internal string PLU;
}
</code>
<code>internal class ILMButtonsProps { internal string ItemGroup; internal string LayoutNumber; internal int Enable; internal string PLU; } </code>
internal class  ILMButtonsProps
{
    internal string ItemGroup;
    internal string LayoutNumber;
    internal int Enable;
    internal string PLU;
}

Here is also the table in the table designer:

When I call the getILMButtonProps function using the next bit of code, I get all of the results in a weird pattern.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>//Load buttons
ILMButtonsProps[] array = SQL.getILMButtonProps(cmbILMGroups.SelectedItem.ToString());
int counter = 0;
int max = array.Length;
Button[] btns = panel4.Controls.OfType<Button>().ToArray();
if (array == null)
{
helperClass.throwError("There was an error reading the arrangements for the buttons in the database! Please try again...", "NPManager");
return;
}
for (int x = 0; x < max; x++)
{
//If all props are set, exit loop
if (counter == max || counter == 35) { break; }
//If there is a null in the layout, skip it.
if (array[counter] == null)
{
counter++;
return;
}
//Enable t/f
//Get details from DB and input to buttons
int i = Convert.ToInt32(array[counter].LayoutNumber);
if (array[counter].Enable == 1)
{
btns[i].Text = "";
btns[i].BackgroundImage = NPManager.Properties.Resources._109_AllAnnotations_Error_24x24_72;
}
if (array[counter].Enable == 2)
{
ILMDataPoints dp = SQL.getDataRowFromPLU(array[counter].PLU);
btns[i].Text = dp.itemName + " @ " + dp.itemPrice;
if(dp.image == null)
{
btns[i].BackgroundImage = null;
btns[i].ForeColor = Color.Black;
}
if (dp.image != null && string.IsNullOrEmpty(dp.image.ToString()) && dp.image == System.DBNull.Value && dp.image.ToString() == "{}")
{
btns[i].BackgroundImage = GetImageFromByteArray((byte[])dp.image);
PictureAnalysis pictureAnalysis = new PictureAnalysis();
btns[i].ForeColor = GetReadableForeColor(pictureAnalysis.GetMostUsedColor(GetImageFromByteArray((byte[])dp.image))); //N
}
}
counter++;
}
</code>
<code>//Load buttons ILMButtonsProps[] array = SQL.getILMButtonProps(cmbILMGroups.SelectedItem.ToString()); int counter = 0; int max = array.Length; Button[] btns = panel4.Controls.OfType<Button>().ToArray(); if (array == null) { helperClass.throwError("There was an error reading the arrangements for the buttons in the database! Please try again...", "NPManager"); return; } for (int x = 0; x < max; x++) { //If all props are set, exit loop if (counter == max || counter == 35) { break; } //If there is a null in the layout, skip it. if (array[counter] == null) { counter++; return; } //Enable t/f //Get details from DB and input to buttons int i = Convert.ToInt32(array[counter].LayoutNumber); if (array[counter].Enable == 1) { btns[i].Text = ""; btns[i].BackgroundImage = NPManager.Properties.Resources._109_AllAnnotations_Error_24x24_72; } if (array[counter].Enable == 2) { ILMDataPoints dp = SQL.getDataRowFromPLU(array[counter].PLU); btns[i].Text = dp.itemName + " @ " + dp.itemPrice; if(dp.image == null) { btns[i].BackgroundImage = null; btns[i].ForeColor = Color.Black; } if (dp.image != null && string.IsNullOrEmpty(dp.image.ToString()) && dp.image == System.DBNull.Value && dp.image.ToString() == "{}") { btns[i].BackgroundImage = GetImageFromByteArray((byte[])dp.image); PictureAnalysis pictureAnalysis = new PictureAnalysis(); btns[i].ForeColor = GetReadableForeColor(pictureAnalysis.GetMostUsedColor(GetImageFromByteArray((byte[])dp.image))); //N } } counter++; } </code>
//Load buttons
ILMButtonsProps[] array = SQL.getILMButtonProps(cmbILMGroups.SelectedItem.ToString());
int counter = 0;
int max = array.Length;
Button[] btns = panel4.Controls.OfType<Button>().ToArray();

if (array == null)
{
    helperClass.throwError("There was an error reading the arrangements for the buttons in the database! Please try again...", "NPManager");
    return;
}

for (int x = 0; x < max; x++)
{
    //If all props are set, exit loop
    if (counter == max || counter == 35) { break; }

    //If there is a null in the layout, skip it.
    if (array[counter] == null)
    {
        counter++;
        return;
    }

    //Enable t/f
    //Get details from DB and input to buttons
    int i = Convert.ToInt32(array[counter].LayoutNumber);
    if (array[counter].Enable == 1)
    {
        btns[i].Text = "";
        btns[i].BackgroundImage = NPManager.Properties.Resources._109_AllAnnotations_Error_24x24_72;
    }

    if (array[counter].Enable == 2)
    {
        ILMDataPoints dp = SQL.getDataRowFromPLU(array[counter].PLU);

        btns[i].Text = dp.itemName + " @ " + dp.itemPrice;
        if(dp.image == null)
        {
            btns[i].BackgroundImage = null;
            btns[i].ForeColor = Color.Black;
        }
        if (dp.image != null && string.IsNullOrEmpty(dp.image.ToString()) && dp.image == System.DBNull.Value && dp.image.ToString() == "{}")
        {
            btns[i].BackgroundImage = GetImageFromByteArray((byte[])dp.image);

            PictureAnalysis pictureAnalysis = new PictureAnalysis();
            btns[i].ForeColor = GetReadableForeColor(pictureAnalysis.GetMostUsedColor(GetImageFromByteArray((byte[])dp.image))); //N
        }
    }

    counter++;
}

The ILMDatapoints (dp) variable is a custom class

Here is the result:

As you can see, the buttons arrangement is alternating from the top and bottom, but I want it to be from left to right. I don’t understand how this is possible, as I am using multiple ways to ensure that the buttons and properties are in their correct order (numerical order). When I debug the the button array above, it shows that they’re in the correct order, although I think this may be wrong, as I see it as the only point where the buttons could get messed up.

6

For anyone in the future who needs the solution, it is to sort the buttons in the btns[]

Here is what I did:
Button[] btns = panel4.Controls.Cast<Button>().OrderBy(x => Convert.ToInt32(x.Tag)).ToArray();

Here is the result:

I used the tag on the buttons to make this possible.

Thank you to Fildor (see comment on problem above) and Lân Vũ for the solution.

Try ordering by the layoutnumber in the SQL query

New contributor

Diogo Ribeiro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật