获取CheckBoxList的选定值

时间:2014-01-15 10:45:04

标签: c# asp.net linq checkboxlist

所以我从获取CheckBoxList中的值时遇到了这个问题 - 我能够从所选的那些中获取“文本” - 但是这些值并不那么容易。

我想要完成的是,对于所选的值,有一个数字,对于每个选择的我想要将该值乘以其选定的值。如果这有意义吗?

到目前为止我的完整代码是:

{
    MailMessage mail = new MailMessage();
    SmtpClient client = new SmtpClient();

    client.Port = 587;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    client.DeliveryFormat = SmtpDeliveryFormat.International;
    client.Timeout = 10000;
    client.Credentials = new System.Net.NetworkCredential("myemail@mail.com", "myPassword");

    if (this.fiUpload1.HasFile)
    {
        this.fiUpload1.SaveAs(Server.MapPath("MyAttach/" + fiUpload1.FileName));
        mail.Attachments.Add(new Attachment(Server.MapPath("MyAttach/" + fiUpload1.FileName)));
    }
    //Gets the selected text from the checkboxlist
    string items = string.Empty;
    foreach (ListItem i in checkedUsers.Items)
    {
        if (i.Selected == true)
        {
            items += i.Text + ",";
        }
    }

    mail.To.Add(new MailAddress("mail@mail.com"));
    mail.From = new MailAddress("mail@mail.com");
    mail.Subject = txtSubject.Text;
    mail.Body = "Ekstra informasjon fra kunde : " + txtBody.Text + " Kunden sine valgte produkter for bestilling : " + items;

    client.Send(mail);

    Label1.Text = "Bestilling sendt ! ";
}

因此我们可以看到mail.body,它已经设法获取所选的“文本”或“项目”来调用它。如上所述,我还希望它包含每个所选项目的值,并将它们一起添加为总数。

1 个答案:

答案 0 :(得分:1)

Imho这个带有SumString.Join的LINQ查询(用逗号连接)更具可读性:

var selectedItems = checkedUsers.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .Select(li => int.Parse(li.Text));
int sum = selectedItems.Sum();
string items = string.Join(",", selectedItems);