2014-01-15 86 views
1

因此,我從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("[email protected]", "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("[email protected]")); 
    mail.From = new MailAddress("[email protected]"); 
    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,它已經設法得到所選擇的「文本」或「項目」來稱呼它。如上所述,我還希望它包含每個選定項目的值並將它們加在一起以獲取總數。

+0

請提供您的ASPX代碼 –

回答

1

恕我直言,這LINQ查詢與SumString.Join(以Concat的所有逗號)更具有可讀性:

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);