我想创建一个包含gridview的邮件。我一直在网上搜索并尝试了多种解决方案。但不知何故,我误解或做错了什么。使用我当前的代码,我收到错误:
System.InvalidOperationException: Data source is an invalid type. It must be either
an IListSource, IEnumerable, or IDataSource.
我读过有关使用StringBuilder
,StringWriter
,HtmlTextWriter
,RenderControl
等内容,但仍然无法弄清楚如何使用此功能。
这是我的代码:
public void Email()
{
string conn = "Data Source=pc-..";
System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(conn);
sqlConn.Open();
SqlCommand sendGrid = new SqlCommand("SELECT * FROM tblSomething", sqlConn);
GridView grd = new GridView();
if (sendGrid != null)
{
grd.DataSource = sendGrid.ExecuteReader();
grd.DataBind();
}
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
grd.RenderControl(htw);
MailMessage mail = new MailMessage();
mail.To.Add("ToWhoEmail");
mail.From = new MailAddress("FromWho");
mail.Subject = "SubjectSomething";
mail.IsBodyHtml = true;
mail.BodyFormat = System.Net.Mail.MailMessage.IsBodyHtml.Html;
// At this line above i get an error. He doesn't recognize BodyFormat = ...;
// System.Web.Mail.MailFormat is obsolete.
// The recommended alternative is: System.Net.Mail.MailMessage.IsBodyHtml
mail.Body = sb.ToString();
SmtpClient smtp = new SmtpClient("...");
smtp.Send(mail);}
我还尝试在不同的cs文件中创建gridview并使用以下命令调用它: mail.Body =“...”中的SendGrid.MakeGrid(); 但我得到的只是:我的电子邮件中的System.Web.UI.WebControls.GridView。 感谢所有帮助,提前谢谢。
问候,Mati
答案 0 :(得分:4)
问题在于这一行:
grd.DataSource = sendGrid;
您正尝试将SqlCommand
用作网格视图的数据源,这是不可能的。您可以使用数据读取器或数据集:
grd.DataSource = sendGrid.ExecuteReader();
还要确保通过将这些连接和命令包装在using statements。
中来妥善处理这些连接和命令答案 1 :(得分:2)
在上面的代码中我没有看到邮件发送的smtp设置....设置端口号和服务器访问凭证,如你的用户名和密码的gmail和端口
smtp.gmail.com(使用身份验证)
使用身份验证:是
TLS / STARTTLS的端口:587
SSL端口:465
答案 2 :(得分:1)
对于网格视图数据源,使用sqlcommanad作为数据源是不正确的使用dataadapter ....