Steve C. Orr

Software Engineer, Web Developer, Database Designer
 
  

 







Q: How do I set the focus to a particular control on my page?

A: The Web browser controls this kind of functionality; therefore this must be done via client-side code that runs within the browser. The following JavaScript snippet can be added to the bottom of the HTML view of your page:

<script language="javascript">
      document.getElementById("TextBox1").focus();
</script>

Perhaps it isn't known until run time which control should get the focus. In this case, code similar to the above example could be generated and output dynamically at run time via server-side code. For this, a subroutine like the one shown in Figure 1 could be used.

Private Sub SetFocus(ByVal ctrl As Control)
    Dim sb As New System.Text.StringBuilder
    sb.Append("<script language='javascript'>")
    sb.Append("document.getElementById('")
    sb.Append(ctrl.ClientID)
    sb.Append("').focus();")
    sb.Append("</script>")
    RegisterStartupScript("SetFocus", sb.ToString)
End Sub

Figure 1. This VB.NET code will set the initial focus to any control that is passed to it.

To call the method, simply execute a line of code such as this from the code-behind of a Web page:

SetFocus(TextBox1)



 

Q: How do I send the output of a Web control via e-mail?

A: Assuming SMTP is configured properly on the server, the output of nearly any Web control can be captured via the output of its RenderControl method, and then sent out using the MailMessage class of the System.Web.Mail namespace. Such functionality is provided by the VB.NET method shown in Figure 2, which you can call from the code-behind class of any page.

Private Sub EmailControl(ByVal ctrl As Control,
  ByVal ToEmailAddress As String)
 
    'Get the output of the control
    Dim sb As New System.text.StringBuilder
    Dim sw As New IO.StringWriter(sb)
    Dim tw As New HtmlTextWriter(sw)
    ctrl.RenderControl(tw)
 
    'Send the email
    Dim MailMsg As New Web.Mail.MailMessage
    Dim svr As Web.Mail.SmtpMail
    svr.SmtpServer = "smtp.mydomain.com"
    MailMsg.To = ToEmailAddress
    MailMsg.From = "admin@wherever.com"
    MailMsg.BodyFormat = Mail.MailFormat.Html
    MailMsg.Subject = "Test Email"
    MailMsg.Body = sb.ToString
    svr.Send(MailMsg)
End Sub

Figure 5: This code will grab the HTML output of a control and send it to the specified e-mail address.

This code works well primarily for read-only controls, such as Labels, DataGrids, LinkButtons, etc. Editable controls such as TextBoxes don't tend to work as well because they expect to be hosted inside a form.

Of course, any network administrator will tell you that e-mail is a complex topic involving firewalls, spam filtering systems, and more. Therefore, there are plenty of ways the code in Figure 5 could fail, so (as always) you should employ error handling of one kind or another.


 

(advertisement)