2013-04-30 42 views
0

如何創建新的gridview/datalist並在代碼後填充併發送爲email body? 我已經有一個DataList填充項目,但我不想發送它的所有列。所以,我想用我想要的列生成一個gridview用於發送電子郵件。 下面是我已經這樣做了如何創建新的GridView並在代碼後面填充並作爲電子郵件正文發送?

  GridView gv = new GridView(); 
      DataTable tbl = new DataTable(); 
      tbl.Columns.Add("Items", typeof(string)); 
      tbl.Columns.Add("Price", typeof(string)); 
      tbl.Columns.Add("Total", typeof(string)); 
      List<HiredList> hl = new List<HiredList>(); 
      hl = (List<HiredList>)Session["Hired"]; 
      foreach (var i in hl) 
      { 
       DataRow itms = tbl.NewRow(); 
       itms["Items"] = i.pName; 
       itms["Price"] = i.price; 
       itms["Total"] = i.pTotal; 
      } 
      //use AutoGenerateColumnsto let grid generate the column itself' 
      gv.AutoGenerateColumns = true; 
      gv.DataSource = tbl; 
      gv.DataBind(); 

那麼這個GridView控件發送到

private string GetGridviewData(GridView gvList) 
    { 
     StringBuilder strBuilder = new StringBuilder(); 
     StringWriter strWriter = new StringWriter(strBuilder); 
     HtmlTextWriter htw = new HtmlTextWriter(strWriter); 
     gvList.RenderControl(htw); 
     return strBuilder.ToString(); 
    } 

但作爲回報我只得到,在我收到的電子郵件。 我不知道我犯了什麼錯誤。

+0

到目前爲止,您是否嘗試過任何方法?請閱讀[常見問題]和[問] – 2013-04-30 06:09:00

回答

0

在GridView中發送數據作爲郵件:

public void SendHTMLMail() 
{ 
MailMessage Msg = new MailMessage(); 
MailAddress fromMail = new MailAddress("[email protected]"); 
// Sender e-mail address. 
Msg.From = fromMail; 
// Recipient e-mail address. 
Msg.To.Add(new MailAddress("[email protected]")); 
// Subject of e-mail 
Msg.Subject = "Send Gridivew in EMail"; 
Msg.Body += "Please check below data <br/><br/>"; 
Msg.Body += GetGridviewData(gvUserInfo); 
Msg.IsBodyHtml = true; 
string sSmtpServer = ""; 
sSmtpServer = "10.2.160.101"; 
SmtpClient a = new SmtpClient(); 
a.Host = sSmtpServer; 
a.EnableSsl = true; 
a.Send(Msg); 
} 

//使用這個方法來呈現GridView控件

public string GetGridviewData(GridView gv) 
{ 
StringBuilder strBuilder = new StringBuilder(); 
StringWriter strWriter = new StringWriter(strBuilder); 
HtmlTextWriter htw = new HtmlTextWriter(strWriter); 
gv.RenderControl(htw); 
return strBuilder.ToString(); 
} 

參考鏈接:

http://www.aspdotnet-suresh.com/2012/09/how-to-send-gridview-in-email-body-in.html

對於普通HTML網頁郵件:

http://www.aspdotnet-suresh.com/2012/09/how-to-send-html-page-as-email-body-in.html

對於DataLists:

http://www.dreamincode.net/forums/topic/269410-send-datalist-value-within-contact-page/

希望它有幫助。

+0

我可以發送DataList嗎? – Sana 2013-04-30 06:41:22

+0

閱讀我編輯的答案中的最後一個鏈接 – Freelancer 2013-04-30 06:44:31

+0

請檢查我上面編輯的代碼 – Sana 2013-04-30 10:09:49

相關問題