aianLee
aianLee

Reputation: 61

how to get checkboxlist values to be selected and be displayed

I binded my checkboxlist by:

        string countrySQL = "Select id, CurrencyName From VirtualAccount_Currency";
        string[] param = { };
        object[] paramVal = { };

        return ClassDBQuery.ExecDataReader(countrySQL, param, paramVal);

datalayer:

        string selCurrSQL = "SELECT * FROM VirtualAccount WHERE MerchantMasterID = @id";

        string[] param = { "@id" };
        object[] paramVal = { currID };

        return ClassDBQuery.ExecDataReader(selCurrSQL, param, paramVal);

here is my code:

            DataTable currDT = new DataTable();
            currDT = ClassView.SelectCurrency(idses);

            foreach (DataRow row in currDT.Rows)
            {
                foreach (ListItem item in currencyBox.Items)
                {
                    if (item.Value == (row["CurrencyID"].ToString()))
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }

Now, when i run my code, there is no error encountered but the values of the checkbox are displayed. When I am debugging it, the system only loops in the first foreach the enters the second foreach but doesn't go through the if statement... What's wrong with my code..?

thank you...

Upvotes: 0

Views: 1343

Answers (2)

Saiyam
Saiyam

Reputation: 138

Try This:-

 for (int j = 0; j < CheckBoxList1.Items.Count; j++)
 {
 if (CheckBoxList1.Items[j].Text.Trim() ==row["CurrencyID"].ToString())
 {  
 CheckBoxList1.Items[j].Selected = true;  break;
 }
 }

Hope this helps!!

Upvotes: 0

Damith
Damith

Reputation: 63105

try below,

        foreach (DataRow row in currDT.Rows)
        {
            foreach (ListItem item in currencyBox.Items)
            {
                // check here what you get
                int currencyId= row.Field<int>("CurrencyID");

                if (item.Value == currencyId.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }
        }

if your field CurrencyID can have null values then,

int? currencyId= row.Field<int?>("CurrencyID");

if (currencyId! =null && item.Value == currencyId.ToString())
{
    item.Selected = true;
    break;
}

Upvotes: 1

Related Questions