2

当我没有checkbox在我的选择gridview并按下删除按钮时,它显示错误“没有选中复选框”但是当我选择checkbox并单击删除按钮后它仍然显示该错误不知道为什么?我没有使用任何数据库,我只是使用datatableand gridview

这是我在删除按钮上的代码

protected void DeleteButton_Click(object sender, EventArgs e)
{

    var dt = (DataTable)ViewState["CurrentData"];

    if (dt == null)
    {
        return;
    }
    List<DataRow> rowsToDelete = new List<DataRow>();
    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
        if (cb != null && cb.Checked)
        {
            row.Visible = false;

            //remove row by its index as it should GridViewRow index == DataRow index
            //it is not the best way but from your code I dont have information how your GridView looks
            dt.Rows.RemoveAt(row.RowIndex);

            GridView1.DataSource = dt;
            GridView1.DataBind();

            GridView2.DataSource = dt;
            GridView2.DataBind();

            ViewState["CurrentData"] = dt;
        }
        else
        {
            lblError.Visible = true;
        }
        for (int i = 0; i < rowsToDelete.Count; i++)
        {
            dt.Rows.Remove(rowsToDelete[i]);
        }
    }
4

3 回答 3

0

我认为你必须使用

if (!Page.IsPostBack)
{

}

页面加载功能

于 2013-02-09T10:34:55.373 回答
0
lblError.Visible = true;

将控件设置为可见后,所有回发都会记住该控件是可见的,并将继续显示该控件。你有两个选择:

  • lblError.Visible = false;没有错误时在您的代码中显式设置。
  • 更改lblError您的.aspx文件以设置EnableViewStatefalse.

实际上,仔细观察:您的逻辑还有其他问题需要解决。您检查每一行,如果任何行的复选框未选中,则设置lblError.Visibletrue. 根据您的文本lblError,您只需在所有行的复选框都未选中时使其可见。

bool allUnchecked = true;
foreach (GridViewRow row in GridView1.Rows)
{
    CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
    if (cb != null && cb.Checked)
    {
        /* your existing code here */

        allUnchecked = false;
    }
    /* no else branch here */

    for (int i = 0; i < rowsToDelete.Count; i++)
    {
        dt.Rows.Remove(rowsToDelete[i]);
    }
}
lblError.Visible = allUnchecked;
于 2013-02-09T10:37:59.430 回答
0

请运行此代码。

 protected void Button2_Click(object sender, EventArgs e)
 {
    var dt = (DataTable)ViewState["CurrentData"];

    if (dt == null)
    {
        return;
    }

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox cb = (CheckBox)row.FindControl("CheckBox2");
        if (cb != null && cb.Checked)
        {
            Label1.Visible = false;
            dt.Rows.RemoveAt(row.RowIndex);
            GridView1.DataSource = dt;
            GridView1.DataBind();

            GridView2.DataSource = dt;
            GridView2.DataBind();

            ViewState["CurrentData"] = dt;
        }
        else if (cb.Checked == false)
        {
            Label1.Visible = true;
        }
    }

}
于 2013-02-09T10:56:38.477 回答