views:

108

answers:

1

I have a "Clear" button which sets the gridview datasource to null and binds it. However, when I add a new entry to it, the old rows seem to show up again (in addition to the new row)...not sure what I am doing wrong....

gv.DataSource = null;
gv.DataBind();

Shouldn't the above clear out the state of the gridview? TIA

  protected void btnAddFactor_Click(object sender, EventArgs e)
    {

        if (txtfactor.Text != "")
        {
            if (ViewState["factor"] == null)
            {
                DataTable dtbl = new DataTable();
                dtbl.Columns.Add("Factor");
                dtbl.Columns.Add("Weight");
                DataRow dr = dtbl.NewRow();
                dr[0] = txtfactor.Text.Trim();
                dr[1] = Convert.ToInt32(ddlWeight.SelectedValue);
                dtbl.Rows.Add(dr);
                ViewState["factor"] = dtbl;

            }
            else
            {

                DataTable dtbl = (DataTable)(ViewState["factor"]);
                DataRow dr = dtbl.NewRow();
                dr[0] = txtfactor.Text.Trim();
                dr[1] = Convert.ToInt32(ddlWeight.SelectedValue);
                dtbl.Rows.Add(dr);
                ViewState["factor"] = dtbl;

            }
            gvFactor.DataSource = (DataTable)(ViewState["factor"]);
            gvFactor.DataBind();
            //gvFactor.Rows.

        }
    }

   protected void btnClearFactor_Click(object sender, EventArgs e)
    {
        gvFactor.DataSource = null;
        gvFactor.DataBind();
    }
+1  A: 

Are you sure that code is being executed?

If that doesn't run the viewstate gets applied and the row (or anything else you have) doesn't go away.

Please, include the method that contains that code and the related markup.

Update:

Ok, I am looking at the code you added, you saving the stuff in the viewstate, when you clear the gridView and rebind you need to also clear the ViewState (ViewState["factor"] == null), otherwise when you add the other row the old one gets picked up as well as it is still in the viewState:

protected void btnClearFactor_Click(object sender, EventArgs e)
{
    ViewState["factor"] == null

    // this line you shouldn't need
    gvFactor.DataSource = null;

    gvFactor.DataBind();
}

If you clear the ViewState setting the DataSource to null is also not needed.

JohnIdol
Yes it is..I can see the gv being cleared. However, when I add a new row, the old ones reappear.
Mikos
works great! thanks so much!
Mikos
if you don't mind, also vote up if it worked ;)
JohnIdol