Domanda

so I got this problem with getting the values from a CheckBoxList - I was able to get the "text" from the selected ones - But with the values its not that easy.

What I want to accomplish is that for the selected values there's a number and for each selected I want to multiply the value by its selected values . If that made any sense?

My complete code so far is :

{
    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 ! ";
}

So as we can see for the mail.body, it already manages to get the selected "text" or "items" to call it that. As mentioned above I also want it to contain the values of each selected item and add them together for a total number.

È stato utile?

Soluzione

Imho this LINQ query with Sum and String.Join(to concat all with comma) is more readable:

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top