我在执行以下代码时遇到问题,我正在创建一个电子邮件系统,我可以通过单击gridview中的复选框来选择多个电子邮件。一旦我选择了我想要的电子邮件并点击发送按钮,我收到以下错误
指数超出范围。必须是非负数且小于集合的大小。 参数名称:index
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.ArgumentOutOfRangeException:索引超出范围。必须是非负数且小于集合的大小。 参数名称:index
以下是我的代码 任何帮助表示赞赏
protected void send_Click(object sender, EventArgs e)
{
//Array list to hold selected email ids
ArrayList emailArray = new ArrayList();
//Looping through rows of GridView
foreach (GridViewRow item in GridView1.Rows)
{
//Creating checkbox object using the find control method
CheckBox cb = (CheckBox)item.Cells[1].FindControl("CheckBox1");
//CheckBox cb = (CheckBox)item.FindControl("CheckBox1");
//Checking whether checkbox is checked or not
if (cb.Checked)
{
//If checked Adding email id to Arraylist
emailArray.Add(GridView1.DataKeys[item.RowIndex]["email"].ToString());
}
}
//Looping through the email id list
foreach (string email in emailArray)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("siscsc3047@gmail.com");
msg.To.Add(email);
msg.Subject = subjecttext.Text;
msg.Body = TextBox1.Text;
SmtpClient smt = new SmtpClient("smtp.gmail.com", 587);
smt.Credentials = new System.Net.NetworkCredential("siscsc3047@gmail.com", "xxxxxxxxx");
smt.EnableSsl = true;
smt.Send(msg);
//}
}
emailsent.Text = "Email has been sent Successfully";
}
}
<asp:GridView ID="GridView1" runat="server" Visible="true"
CssClass="mydatagrid" EmptyDataText="No Students Enrolled on this Module"
EmptyDataRowStyle-BorderWidth="0px" PagerStyle-CssClass="pager"
HeaderStyle-CssClass="header" RowStyle-CssClass="rows"
DataSourceID="displayemail">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="email" HeaderText="email" SortExpression="name" />
</Columns>
</asp:GridView>
答案 0 :(得分:0)
您缺少的是设置GridView的DataKeyName
属性。您的GridView
应更改如下。
<asp:GridView ID="GridView1" runat="server" Visible="true"
CssClass="mydatagrid" EmptyDataText="No Students Enrolled on this Module"
EmptyDataRowStyle-BorderWidth="0px" PagerStyle-CssClass="pager"
HeaderStyle-CssClass="header" RowStyle-CssClass="rows"
DataSourceID="displayemail" DataKeyNames="email">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="email" HeaderText="email" SortExpression="name" />
</Columns>
</asp:GridView>