[Javascript version, codebehind version to be submitted by szlamany]
This code sample is useful if you want to open the user's email client (Outlook, Outlook Express, Windows Live Mail, etc.) from your ASP.NET page and if your gridview contains checkboxes to select to whom the email will go to.
In my ASPX, I first make the javascript.
Code:
<script type="text/javascript">
Array.prototype.remove=function(str)
{
for(i=0;i<this.length;i++)
{
if(this[i]==str)
{
this.splice(i, 1);
}
}
}
var EmailAddresses = new Array();
function AddRemoveEmailAddress(chk, emailaddress)
{
if(chk.checked == true)
{
EmailAddresses.push(emailaddress);
}
else
{
EmailAddresses.remove(emailaddress);
}
}
function SendEmails()
{
var emailString = "";
for(i=0;i<EmailAddresses.length;i++)
{
emailString += EmailAddresses[i] + ";";
}
document.location.href='mailto:' + emailString;
}
</script>
Then, setup the gridview and button.
Code:
<div>
<asp:GridView ID="Students" Runat="server" OnRowDataBound="Students_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSendMail" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<input type="button" onclick="javascript:SendEmails();" value="Send" id="EmailButton" />
</div>
Then in the codebehind, I first setup a dummy datatable.
vb Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dt As New Data.DataTable()
dt.Columns.Add("col1")
dt.Columns.Add("col2")
dt.Columns.Add("col3")
Dim dr As Data.DataRow = dt.NewRow()
dr.Item("col1") = "111"
dr.Item("col2") = "222"
dr.Item("col3") = "gremlins@york.net"
Dim dr2 As Data.DataRow = dt.NewRow()
dr2.Item("col1") = "333"
dr2.Item("col2") = "444"
dr2("col3") = "szlamany@philosophy.org"
Dim dr3 As Data.DataRow = dt.NewRow()
dr3.Item("col1") = "555"
dr3.Item("col2") = "666"
dr3.Item("col3") = "hamburgers@microsoft.com"
dt.Rows.Add(dr)
dt.Rows.Add(dr2)
dt.Rows.Add(dr3)
Students.DataSource = dt
Students.DataBind()
End Sub
And finally the main bit, the RowDataBound event wherein I give each checkbox an onClick javascript method to call which adds or removes the email address from the global javascript array defined earlier.
vb Code:
Protected Sub Students_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Students.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim chk As New CheckBox
chk = e.Row.FindControl("chkSendMail")
chk.Attributes.Add("onClick", "AddRemoveEmailAddress(this, '" & CType(e.Row.DataItem, Data.DataRowView).Item("col3").ToString() & "');")
End If
End Sub
Ta-daaaa.
Keywords:
email
gridview
checkboxes
client side