繁体   English   中英

ASP.NET C#:发生错误:索引超出范围。 必须为非负数并且小于集合的大小。 参数名称:索引(GRIDVIEW)

[英]ASP.NET C#: Error occured: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index (GRIDVIEW)

我不知道出了什么问题。 我试图通过在gridview中使用复选框选项来选择向哪个用户发送电子邮件,但是在按发送后,错误告诉我索引超出范围。

HTML标记:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
     AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" 
     DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
            <asp:BoundField DataField="email" HeaderText="email" SortExpression="email" />

        <asp:TemplateField HeaderText="CheckAll">
                <HeaderTemplate>
                    <asp:CheckBox ID="chkSelectAll" runat="server"
                                  AutoPostBack="true"
                                  OnCheckedChanged="chkSelectAll_CheckedChanged"/>Send Mail To All ?
                </HeaderTemplate>
                    <ItemTemplate>
                    <asp:CheckBox ID="chkSelect" runat="server"/>
                    </ItemTemplate>
                 </asp:TemplateField>


            <asp:BoundField DataField="gender" HeaderText="gender" SortExpression="gender" />
            <asp:BoundField DataField="dateOfBirth" HeaderText="dateOfBirth" SortExpression="dateOfBirth" />
            <asp:BoundField DataField="contactNo" HeaderText="contactNo" SortExpression="contactNo" />
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EBizProjectConnection %>" SelectCommand="SELECT [username], [email], [gender], [dateOfBirth], [contactNo] FROM [Users] WHERE (([newsletter] = @newsletter) AND ([accountType] = @accountType))">
        <SelectParameters>
            <asp:Parameter DefaultValue="yes" Name="newsletter" Type="String" />
            <asp:Parameter DefaultValue="user" Name="accountType" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

后面的C#代码:

public partial class Pages_StaffSendingNewsletter : System.Web.UI.Page
{
    protected void btnSend_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnection"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    { }
        string UserID = string.Empty;
        DataTable dt = new DataTable();
        try
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("chkSelect");

                if (cb.Checked == true)
                {
                    if (cb != null && cb.Checked)
                    {
                        UserID = Convert.ToString(GridView1.DataKeys[row.RowIndex].Value);
                        SqlCommand cmd = new SqlCommand("select email from Users where UserID=" + UserID + "", conn);
                        SqlDataAdapter adp = new SqlDataAdapter(cmd);

                        adp.Fill(dt);

                        string email = dt.Rows[0]["email"].ToString();

                        SendEmailUsingGmail(email);
                        dt.Clear();
                        dt.Dispose();
                    }
                }
            }

            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Emails sent successfully');", true);
        }
        catch (Exception ex)
        {
            Response.Write("Error occured: " + ex.Message.ToString());
        }
        finally
        {
            UserID = string.Empty;
        }
    }

    private void SendEmailUsingGmail(string toEmailAddress)
    {
        try
        {
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential("jiadapeh@gmail.com", "helloapple");
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;

            MailAddress from = new MailAddress("jiadapeh@gmail.com");
            string body = "Hello {1}, Thank you for subscribing to Jabez Events inc <br />" + txtBody.Text;
            //       MailMessage mail = new MailMessage(txtSubject.Text, body);
            MailMessage mail = new MailMessage();
            mail.From = from;
            mail.To.Add(toEmailAddress);
            mail.Subject = txtSubject.Text;
            mail.IsBodyHtml = true;
            mail.Body = body;
            //client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Send(mail); 
        }
        catch (Exception ex)
        {
            Response.Write("Error occured: " + ex.Message.ToString());
        }
    }

    protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkAll =
           (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
        if (chkAll.Checked == true)
        {
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel =
                     (CheckBox)gvRow.FindControl("chkSelect");
                chkSel.Checked = true;
            }
        }
        else
        {
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                chkSel.Checked = false;
            }
        }
    }
}

实际解决了它,因为我最初没有将“ UserID”添加到我的gridview中。 抱歉,该职位。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM