barjed
barjed

Reputation: 387

GridView selects wrong row for editing

I have a simple admin panel with a simple gridview that list all articles present in the database.

I've added a filtering doodle (a textbox + a button) that allows the user to filter the gridview by a article name.

The code for the filter:

    protected void ButtonSearchArticle_Click(object sender, EventArgs e)
    {
        {
            LinqDataSourceAdminArticles.Where = "Title.Contains(" + "\"" + TextBoxSearchArticle.Text + "\")";
            LinqDataSourceAdminArticles.DataBind();
        }
        LinqDataSourceAdminArticles.DataBind();
    }

The gridview has the default quick editing and deleting enabled on it. The problem is, after I filter it with that code, it starts to select wrong rows when I click the "edit" button. Any ideas how to solve this? I know it has something to do with a postback.

I've checked Why is My GridView FooterRow Referencing the Wrong Row? and Sorted gridview selects wrong row but those didn't solve my problem.

Thanks!

Upvotes: 1

Views: 2411

Answers (2)

John Wilson
John Wilson

Reputation: 1

//Your Page Load Event    
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["s_event"] = "0"; // Initialize session variable
            BindData(); // Gridview Binding
        }

    } 

 protected void BindData()
    {
        if ((Session["s_event"].ToString())=="1")
        {
            cmdstr_ = (Session["search_item"].ToString());
        }
        else
        {
            cmdstr_ = ""; // Your command string to populate gridview

        }
        //        `enter code here`
    }

 protected void btnSearch_Click(object sender, EventArgs e)
    {
        Session["s_event"] = 1; // Search Event becomes 1.

        // Your Search Logic here

        Session["search_item"] = cmdstr;

        // Bind Gridview here

    }

Upvotes: 0

Ali
Ali

Reputation: 838

When you change the GridView's Select query in your button click, it only take effects for that request. because GridView's edit command causes a postback, and in the postback the Gridview works with visible index of the edited row but without the filtering. the best thing to do is to remove your ButtonSearchArticle_Click code and put it into your Page_Load code like this

 if (TextBoxSearchArticle.Text != ""){
        LinqDataSourceAdminArticles.Where = "Title.Contains(" + "\"" + TextBoxSearchArticle.Text + "\")";
        LinqDataSourceAdminArticles.DataBind();

    LinqDataSourceAdminArticles.DataBind();}

Upvotes: 2

Related Questions