I am working on an assignment that is asking me to use code to create a gridview with a checkbox. After doing so, I am to take the checkbox items selected (through a button click) over to the listbox to display the values as text.
The sample page is here: http://aspnet.cob.ohio.edu/mis3200/asppub/MIS3200/Unit8/bobcat8POS.aspx
My code so far is this:
protected void btnSelect_Click(object sender, EventArgs e)
{
lblAlready.Text = string.Empty; // empty the label that says you already have an item
foreach (GridViewRow row in gvSnacktastic.Rows) // check all the items in the grid view
{
CheckBox checkItOut = row.Cells[0].Controls[0] as CheckBox; // get the checkbox
if (checkItOut != null && checkItOut.Checked) // if the checkbox exists and is checked
{
bool storeVariable = true; // store a variable that tells us if we need to add it to the list
foreach(ListItem listItem in lbSelected.Items) // Loop through list box items to see if we already have it. i haven't used listbox in a long time, this might be slightly wrong
{
// I'm not sure if it's .Text - compare the text of the listbox item to the checkbox item description
if(listItem.Text== checkItOut.Text)
{
lblAlready.Text = "The Item " + listItem.Text + " has already been added."; // make our already added label
storeVariable = false; // we don't need to add this item
}
}
if(storeVariable) // if we do need to add this item
{
lbSelected.Items.Add(checkItOut.Text); // create a new list box item with the check box item's description
}
}
}
}
It doesn't display any errors, but when I run the page the select button does not do what I want it to. Would anyone be willing to look at the sample page and let me know what I am missing in my code?
<asp:GridView ID="gvSnacktastic" runat="server" AutoGenerateColumns="False"
DataKeyNames="SID" DataSourceID="sdsSnacktastic" Visible="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbSnacktastic" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowSelectButton="True" Visible="False" />
<asp:BoundField DataField="SID" HeaderText="SID" InsertVisible="False"
ReadOnly="True" SortExpression="SID" Visible="False" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Price" DataFormatString="{0:c2}" HeaderText="Price"
SortExpression="Price" />
</Columns>
</asp:GridView>