このようにページにプレースホルダーを定義しました。
<asp:PlaceHolder ID="attrPlaceHolder" runat="server"></asp:PlaceHolder>
次のようなクエリ文字列productIdを使用して、データベーステーブルからこのプレースホルダーにデータを入力しています。
// obtain the attributes of the product
DataTable attrTable = CatalogAccess.GetProductAttributes(productId);
// temp variables
string prevAttributeName = "";
string attributeName, attributeValue, attributeValueId;
// current DropDown for attribute values
Label attributeNameLabel;
DropDownList attributeValuesDropDown = new DropDownList();
// read the list of attributes
foreach (DataRow r in attrTable.Rows)
{
// get attribute data
attributeName = r["AttributeName"].ToString();
attributeValue = r["AttributeValue"].ToString();
attributeValueId = r["AttributeValueID"].ToString();
// if starting a new attribute (e.g. Color, Size)
if (attributeName != prevAttributeName)
{
prevAttributeName = attributeName;
attributeNameLabel = new Label();
attributeNameLabel.Text = "<li class=\"txt\">" + attributeName + ":</li>";
attributeValuesDropDown = new DropDownList();
attrPlaceHolder.Controls.Add(attributeNameLabel);
attrPlaceHolder.Controls.Add(attributeValuesDropDown);
}
// add a new attribute value to the DropDownList
attributeValuesDropDown.Items.Add(new ListItem(attributeValue, attributeValueId));
}
ただし、ボタン クリック イベント内で、ビジュアル スタジオのデバッグを使用してこの場所をループすると、ビジュアル スタジオ スタジオのデバッガーが foreach ループで最初に「attrPlaceHolder.Controls」という単語をヒットし、次に「in」キーワードに到達することがわかりました。 (foreach ループ内) しかし、最初の 2 つの単語 (つまり、foreach ループ内の 'Control cnt' ) にはヒットしていません。
protected void ButtonBuyNow_Click(object sender, EventArgs e)
{
// Retrieve the selected product options
string options = "";
foreach (Control cnt in attrPlaceHolder.Controls)
{
if (cnt is Label)
{
Label attrLabel = (Label)cnt;
options += attrLabel.Text;
}
if (cnt is DropDownList)
{
DropDownList attrDropDown = (DropDownList)cnt;
options += attrDropDown.Items[attrDropDown.SelectedIndex] + "; ";
}
}
// Add the product to the shopping cart
ShoppingCartAccess.AddItem(productId, options);
}
基本的に、「オプション」変数を設定する必要がありますが、内部で foreach ループにヒットしていないため、「オプション」変数を設定できません。これは私のアプリケーションでは深刻な問題です。foreach ループの内部を取得できない理由を教えてください。
注: これはページ全体の完全なコードではないことに注意してください。残りのコードは正しく実行されます。