Reputation: 1779
I have a datalist control where there are one checkbox in each ItemTamplate. Along with the checkbox there is also a hyperlink to display some documents. Users should be able to click on a checkbox which will display the corresponding document in a Label Control, using StringBuilder. The code below is almost working but it shows duplicates: For example, if I select a checkbox in row 1 and then select another checkbox in row 2 then the Label control will display the document from row 1 twice and then display the document from row 2 once. Here is the relevant code. Thanks!
<tr runat="server" id="tr_data">
<td>
<asp:CheckBox runat="server" ID="cb_docid" Value='<%# Eval("docid") %>' OnCheckedChanged="displayselectedinit"
AutoPostBack="true" />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
protected void displayselected()
{
//return;
lbl_currselection.Text = "";
StringBuilder docselected = new StringBuilder();
foreach (DataListItem li in DataList1.Items)
{
if (li.ItemType == ListItemType.Item || li.ItemType == ListItemType.AlternatingItem)
{
CheckBox cb = li.FindControl("cb_docid") as CheckBox;
if (cb != null)
{
if (cb.Checked)
{
HyperLink hpl_docfile = li.FindControl("hpl_docfileencr") as HyperLink;
docselected.Append(hpl_docfile.Text + "<br />");
lbl_currselection.Text += docselected;
}
}
}
}
}
Upvotes: 0
Views: 3748
Reputation: 460228
This works:
protected void DisplaySelected(Object sender, EventArgs e)
{
var selected = DataList1.Items.Cast<DataListItem>()
.Where( li => ((CheckBox)li.FindControl("cb_docid")).Checked)
.Select(li => ((HyperLink)li.FindControl("hpl_docfileencr")).Text);
lbl_currselection.Text = String.Join("<br />", selected);
}
Upvotes: 1
Reputation: 1010
docselected.Append(hpl_docfile.Text + "<br />");
lbl_currselection.Text += docselected;
You are appending the stringbuilder, as well as adding the label.
Currently, the code is executing this way:
First loop:
Adding: Text1
docselected = Text1<br/>
lbl_currselection = Text1<br/>
Second Loop:
Adding: Text2
docselected = Text1<br/>Text2<br/>
lbl_currselection = Text1<br/>Text1<br/>Text2<br/>
I would move the lbl_currselection.Text to the end (out of the loop) and use:
foreach (DataListItem li in DataList1.Items)
{
if (li.ItemType == ListItemType.Item || li.ItemType == ListItemType.AlternatingItem)
{
CheckBox cb = li.FindControl("cb_docid") as CheckBox;
if (cb != null)
{
if (cb.Checked)
{
HyperLink hpl_docfile = li.FindControl("hpl_docfileencr") as HyperLink;
docselected.Append(hpl_docfile.Text + "<br />");
}
}
}
}
lbl_currselection.Text = docselected;
Upvotes: 1