Sending Datagridview to email

后端 未结 3 591
无人及你
无人及你 2021-01-07 03:23

i made a code that i can send an email to gmail.com with c# and it is working very well. Now i want to put my datagridview1 in the email body and send it. Somone can show me

相关标签:
3条回答
  • 2021-01-07 04:09

    The DataGridView is a WinForm-Control (or: an object) in the first place. What you could do is, for example:

    1. walk through all data items of the dgv and create a table or list to set this to the email body.

    2. you could export the whole object via serialization to xml/json, if you want to export not only the content but the whole object structure.

    3. You also can add the serialized object as an attachment to the email.

    0 讨论(0)
  • 2021-01-07 04:22

    DataGridView is a special tool of the Dot Net and your email (which gets open in a browser) doesn't know anything about it.

    Besides, mail.Body accepts a string value :). you just cannot assign an entire datagridview to it i.e.

    mail.Body = dataGridView1.ToString(); //wrong, utter useless
    

    However, browsers does know about html. lets do one thing, lets create equivalent html table of your dataGridView

    So what you should do is to iterate through each of the rows of your GridView and create html string and assign it to the mail.Body.

    do something like below in your method:

     private void btnSend_Click_1(object sender, EventArgs e)
     {
          string mailBody = "<table width='100%' style='border:Solid 1px Black;'>";
    
          foreach (DataGridViewRow row in dataGridView1.Rows)
          {
                mailBody +="<tr>";
                foreach (DataGridViewCell cell in row.Cells)
                {
                   mailBody +="<td stlye='color:blue;'>" +cell.Value + "</td>";
                }
                mailBody +="</tr>";
          }
          mailBody +="</table>";
    
          //your rest of the original code
          mail.Body = mailBody;
          client.Send(mail); 
    
     }      
    
    0 讨论(0)
  • 2021-01-07 04:30

    You need to iterate over the Rows collection of your datagridview, extract the values and assign to your mail.Body. A crude example: -

    StringBuilder sb = new StringBuilder();
    foreach (DataRow row in datagridview1.Rows)
    {
          sb.AppendLine(row["ROW NAME"].ToString());
    }
    
    mail.Body = sb.ToString();
    
    0 讨论(0)
提交回复
热议问题