OnRowDeleting中的GridView没有找到任何行

时间:2016-04-20 23:51:44

标签: c# asp.net gridview

我在页面上有几个GridView,他们都有问题。当触发OnRowDeleting函数时,GridView(和发送​​者)找不到任何行。我用以下方式创建了GridView:

        <asp:GridView ID="gridview9" runat="server" 
        DataKeyNames="id" 
        OnRowDeleting="deleteNumberFrom9" 
        AutoGenerateColumns="false"
        CssClass="mGrid"
        AlternatingRowStyle="alt">
        <Columns>
            <asp:boundfield datafield="product_key" headertext="PRODUCT KEY"  ItemStyle-HorizontalAlign="Center" />
            <asp:boundfield datafield="first_name" headertext="FIRST NAME"/>
            <asp:boundfield datafield="last_name" headertext="LAST NAME"/>
            <asp:boundfield datafield="email" headertext="EMAIL"/>
            <asp:boundfield datafield="phone_number" headertext="PHONE NUMBER"  ItemStyle-HorizontalAlign="Center" />
            <asp:CommandField HeaderText="DELETE NUMBER" ShowDeleteButton="True"  ItemStyle-HorizontalAlign="Center" DeleteText="Delete" />
        </Columns>
    </asp:GridView>   

网格从MySQL数据库中填充:

    GridView gv = gridview9;
    String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ToString();
    MySqlConnection connection = new MySqlConnection(connectionString);
    connection.Open();
    MySqlCommand command = new MySqlCommand(queryString, connection);
    if (addPhone)       command.Parameters.AddWithValue("@phone_number", "%" + phoneNumber + "%");
    if (addEmail)       command.Parameters.AddWithValue("@email", "%" + email + "%");
    if (addFirstName)   command.Parameters.AddWithValue("@first_name", "%" + firstName + "%");
    if (addLastName)    command.Parameters.AddWithValue("@last_name", "%" + lastName + "%");
    if (addProductKey)  command.Parameters.AddWithValue("@product_key", "%" + productKey + "%");
    MySqlDataAdapter adapter = new MySqlDataAdapter(command);
    System.Data.DataSet ds = new System.Data.DataSet();
    adapter.Fill(ds);
    gv.DataSource = ds;
    gv.DataBind();
    gv.Visible = true;

最后,onRowDeleting函数是:

    protected void deleteNumberFrom9(object sender, GridViewDeleteEventArgs e)
    {
        int SID = Convert.ToInt32(gridview9.DataKeys[e.RowIndex].Value);
        String phone_number = e.Values[4].ToString();
        deleteNumber(SID, phone_number, 9);
    }

当我运行页面时,gridview9正确返回2行但是当我在其中一行中单击delete并且deleteNumberFrom9被触发时gridview9.Rows.Count为0而不是2.当我将发件人添加到监视列表并查看行数也是0.

1 个答案:

答案 0 :(得分:0)

删除数据库中的记录后,必须将数据重新绑定到GridView:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

protected void gv_Deleting(object sender, GridViewDeleteEventArgs e)
{
    ...
    deleteNumber(SID, phone_number, 9);
    BindData();
}

private void BindData()
{
    ...
    gv.DataSource = ds;
    gv.DataBind();
}