Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

GridView values are not refreshing 1

Status
Not open for further replies.

mais123

Programmer
Dec 26, 2007
36
US
I ahev a GridView filled with ASP.NET Texboxes which I create on Grid_DataBind event. we have a functionality where user can change value in a textbox and then revert changes. Revert goes into DB and gets all the old values and reloads the grid, re-creating all the textboxes.

The problem: when the grid refreshes, I still see the new value in the cell(before revert). When I debug ondatabind event, I see that code assigns a correct value to the textbox. So somewhere the incorrect vlaue is being cached?

I disabled ViewState for the page(which is a content page) as well as viewstate for the grid. Also, we're re-creating textboxes each time. What else could it be???

Thanks for any tips!
 
post the code.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Code:
 private void Grid1_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            /// Way to access hidden columns:
            ///Expanded cell
            ///e.Item.Cells[levels]
            ///HasChildren cell
            ///e.Item.Cells[levels + 1]
            ///Level Cell
            ///e.Item.Cells[levels + 2]
            ///Parent Name Cell
            ///e.Item.Cells[levels + 3]
            ///ID Cell
            ///e.Item.Cells[levels + 4]
            // levels + 6 is a start of weeks fields

            //header
            if (e.Item.ItemIndex == -1)
            {
                for (int i = levels + 6; i < e.Item.Cells.Count; i++)
                {
                    //center week headings
                    e.Item.Cells[i].HorizontalAlign = HorizontalAlign.Center;

                    //assign header attributes
                    ////find cell object in collection
                    CellProperties headerProps = (CellProperties)HeaderValuesContainer[i - levels - 6];
                    e.Item.Cells[i].Attributes.Add("oncontextmenu", headerProps.oncontextmenu);
                    e.Item.Cells[i].Attributes.Add("tid", headerProps.tid);
                }
                //replace prod name with "Total" and add scale to label heading
                if (_scaleActivity.ToString()!="1")
                    e.Item.Cells[levels + 5].Text = e.Item.Cells[levels + 5].Text + " (" + _scaleActivity.ToString().Replace("1", "") + ")";

            }
            //replace product name with "Total"
            if (e.Item.ItemIndex == 0)
            {
                e.Item.Cells[levels + 5].Text = "Total";
            }
            // set width for +/- cells
            for (int i = 0; i < levels; i++)
            {
                e.Item.Cells[i].Attributes.Add("Width", "13px");
            }

            //hide columns that should be invisible(Expanded	HasChildren	Level	ParentName)
            HideHiddenColumns(e, levels);
            
            //Measure Name cell
            e.Item.Cells[levels + 5].Attributes.Add("Width", "175px");
            e.Item.Cells[levels + 5].Attributes.Add("Wrap", "false");
            //left-justify the label
            e.Item.Cells[levels + 5].HorizontalAlign = HorizontalAlign.Left;

            //set width rest of the cells(dynamic weeks)
            for (int i = levels + 6; i < e.Item.Cells.Count; i++)
            { e.Item.Cells[i].Attributes.Add("Width", "53px"); }

            //if this is parent(HasChildren) make grey backgroud
            if (e.Item.Cells[levels + 1].Text.ToLower() == "true")
                e.Item.BackColor = System.Drawing.Color.FromArgb(235, 235, 230);
            else// create a link out of measure name. 
            {
                if (e.Item.ItemIndex != -1)
                {
                    //pass it measure name and measure ID
                    //grab first cell
                    CellProperties cellPropsForMeasure = (CellProperties)CellValuesContainer[e.Item.ItemIndex, 0];
                    e.Item.Cells[levels + 5].Attributes.Add("Onclick", "SD('" + e.Item.Cells[levels + 5].Text + "','" + e.Item.Cells[levels + 4].Text + "','" + cellPropsForMeasure.x + "','" + cellPropsForMeasure.y + "')");
                    e.Item.Cells[levels + 5].Style.Add("Cursor", "Hand");
                    //truncate the text 
                    TruncateLabel(e, levels);
                    e.Item.Cells[levels + 5].Text = "<nobr><u>" + e.Item.Cells[levels + 5].Text + "</u></nobr>";
                }
            }

            //Create expand/collapse label
            CreateExpandCollapseButtons(e, Expanded, levels, children, "measure");
            
            if (e.Item.ItemIndex != -1)
            {
                //work with each cell to assign attributes, styles, properties
                for (int i = levels + 6; i < e.Item.Cells.Count; i++)
                {
                    ////find cell object in collection
                    CellProperties cellProps = (CellProperties)CellValuesContainer[e.Item.ItemIndex, i - levels - 6];
                    //create textbox if regular page, label for excel export
                    if (!DoExcel)
                    {
                        System.Web.UI.WebControls.TextBox cellBox = new TextBox();
                        cellBox.EnableViewState = false;
                        //add textbox to the cell
                        e.Item.Cells[i].Controls.Add(cellBox);
                        e.Item.Cells[i].EnableViewState = false;
                        
                        cellBox.CssClass = "GridMeasures";
                        cellBox.BorderStyle = BorderStyle.None;
                        cellBox.Text = e.Item.Cells[i].Text;
                        //remove nbsp(happens when db returns no data)
                        if (cellBox.Text.Trim() == "&nbsp;")
                            cellBox.Text = "";
                        
                        cellBox.Width = 53;
                        ////if HasChildren mark as read only
                        if ((e.Item.Cells[levels + 1].Text.ToLower() == "true"))
                        {
                            cellBox.BackColor = System.Drawing.Color.FromArgb(235, 235, 230);
                            cellBox.ReadOnly = true;
                            cellBox.TabIndex = -1;
                            //indicate if value has been changed
                            cellBox.Attributes.Add("isparent", "1");
                        }
                        else
                            cellBox.Attributes.Add("isparent", "0");
                        //always assign id, no matter if cell is editable
                        cellBox.ID = cellProps.cellId;
                      
                        if ((e.Item.Cells[2].Text.ToLower() == "true"))
                            cellBox.Attributes.Add("rId", cellProps.cellId);

                        if (cellProps.editable)
                        {
                            cellBox.Attributes.Add("pId", cellProps.pId);
                            cellBox.Attributes.Add("oncontextmenu", "return DF();");
                            //cellBox.Attributes.Add("ondblclick", "E(this);");
                            //cellBox.Attributes.Add("onkeydown", "return KD(this);");
                            //cellBox.Attributes.Add("onkeyup", "KU(this);");
                            //cellBox.Attributes.Add("onfocus", "OF(this);");
                            //cellBox.Attributes.Add("onblur", "OB(this);");
                            cellBox.Attributes.Add("x", cellProps.x);
                            cellBox.Attributes.Add("y", cellProps.y);
                            cellBox.Attributes.Add("pr", cellProps.pr);
                            cellBox.Attributes.Add("su", cellProps.su);
                            cellBox.Attributes.Add("mn", cellProps.mn);
                            cellBox.Attributes.Add("mneq", cellProps.mneq);
                            cellBox.Attributes.Add("mx", cellProps.mx);
                            cellBox.Attributes.Add("mxeq", cellProps.mxeq);
                            cellBox.Attributes.Add("dc", cellProps.dc);
                            cellBox.Attributes.Add("ddc", cellProps.ddc);
                            cellBox.Attributes.Add("wk", cellProps.wk);
                            cellBox.Attributes.Add("cf", cellProps.cf);
                            cellBox.Attributes.Add("cp", cellProps.cp);
                            cellBox.Attributes.Add("oldValue", cellBox.Text);
                            cellBox.Attributes.Add("maxLength", "14");
                            cellBox.Attributes.Add("OnFocus", "return HandleFocus(this);");

                            //Event Handlers
                            if ((e.Item.Cells[levels + 1].Text.ToLower() != "true"))
                            {
                                cellBox.Attributes.Add("onblur", "return HandleTextboxBlur(this," + cellProps.dc + ");");
                                cellBox.Attributes.Add("onclick", "return HandleTextboxClick();");
                                cellBox.Attributes.Add("onkeydown", "return HandleKeyDown(this);");
                                cellBox.Attributes.Add("onkeyup", "return HandleKeyUp(this," + cellProps.dc + ");");
                                cellBox.Attributes.Add("onkeypress", "return HandleKeyPress(this);");
                            }
                            //if this is Suggest processing, color the textbox based on ROI
                            if (UserAction.Text.Trim() != "" && Convert.ToInt32(UserAction.Text) == 10 && cellProps.suggestFlag != null)
                            {
                                SetROIColor(cellBox, cellProps.suggestFlag);
                            }
                        }
                        else
                        {
                            cellBox.Attributes.Add("pId", cellProps.pId);
                            cellBox.ReadOnly = true;
                            if (cellProps.cssClass == "redNumbers")
                                cellBox.CssClass = "noEditRedNumbers";
                            else//grey out the non-editable cell 
                                //cellBox.CssClass = "noEdit";
                                cellBox.BackColor = System.Drawing.Color.FromArgb(235, 235, 230);

                        }
                        if (cellProps.toolTip!=null && cellProps.toolTip.Length > 0)
                        {
                            cellBox.ToolTip = cellProps.toolTip;
                            cellBox.Attributes.Add("om", cellProps.toolTip);
                        }

                        //add textbox to the cell
                        //e.Item.Cells[i].Controls.Add(cellBox);

                        string clientId = cellBox.ClientID;
                        string id = cellBox.ID;
                        //update children with correct client id
                        for (int k = 0; k < SpendingRowCount; k++)
                        {
                            for (int j = 0; j < SpendingColCount; j++)
                            {
                                cellProps = (CellProperties)CellValuesContainer[k, j];
                                if (cellProps.pId == id)
                                {
                                    cellProps.pId = clientId;
                                    CellValuesContainer[k, j] = cellProps;
                                }

                            }
                        }
                        //replace old ID with new client ID in the _cells collection
                        _cells.Replace(id, cellBox.ClientID);
                    }
                    else
                    {
                        System.Web.UI.WebControls.Label cellLabel = new Label();
                        cellLabel.CssClass = "GridMeasures";
                        cellLabel.BorderStyle = BorderStyle.None;
                        cellLabel.Text = e.Item.Cells[i].Text;
                        cellLabel.Width = 53;
                        ////if HasChildren mark as read only
                        if ((e.Item.Cells[levels + 1].Text.ToLower() == "true"))
                        {
                            cellLabel.BackColor = System.Drawing.Color.FromArgb(235, 235, 230);
                        }
                    }
                }

                //find row object in collection 
                RowProperties rowProps = (RowProperties)RowValuesContainer[e.Item.ItemIndex];
                //e.Item.Style.Add("display", rowProps.display);
                e.Item.Attributes.Add("pId", rowProps.pId);
                e.Item.Attributes.Add("vId", rowProps.vId);

                //set up indent to Measure cell
                e.Item.Cells[levels + 5].Text = Indent(Convert.ToInt32(e.Item.Cells[levels + 2].Text)) + e.Item.Cells[levels + 5].Text;
            }
            //when we have the last grid item, register cell collection with updated ClientId's
            DataView dv = (DataView)Grid1.DataSource;
            DataTable tbl = dv.ToTable();
            if (e.Item.ItemIndex == tbl.Rows.Count - 1)
            {
                //re-register _cells collection
                string script = String.Format("var _cells = {0};", _cells.ToString());
                if (!RegisterScripts.IsClientScriptBlockRegistered(this, "Cells"))
                {
                    RegisterScripts.RegisterClientScriptBlock(this, "Cells", script, true);
                }

            }
        
        }
 
ok, this very difficult to follow. to figure out whats going on you should create a spike (simple example that reproduces the problem). from there fix the problem. then port the fix over to this situation.

I would also recommend refactoring this procedural code.
1. extract the formatting into a seperate control which formats specific rows and cells.
2. extract the business logic into a seperate object which is only concerned data, not presentation.
3. there are many places where you are using the cell text to set values, instead of pulling the value from the data item. try to avoid using the cell text as this is html specific. instead cast the DataItem to a DataRow and pull values from the DataRow. (this may be where your problem lies as well.)
Code:
//preferred
DataRow row = (DataRow)e.Item.DataItem;
string someData = (string)row["Column Name"];

//or if you are using strongly typed datasets
StronglyTypedDataRow row = (StronglyTypedDataRow)e.Item.DataItem;
string someData = row.ColumnNameForSomeData;

//discouraged
string someData = e.Item.Cells[i].Text;
4. you may want to parse pieces of the gridview into ascx files and just add them as needed. this would also reduce if statements and formatting (by having small web user controls to preform a specific task.)

a different approach would be to discard the gridview and use a repeater instead, this way you have full control over the item rendering. this would also lend itself to use ascx files for specific items states.

if your using 3.0 or 3.5 the ListView would be your best option for complex table structures. this gives you the power of a repeats (full control of html) and the ability to edit, insert, page (gridview features)

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
well, i got into Render event and I see that we're sending incorrect value to the client there. And in OnDataBind, i see the textbox is getting the correct value. I checked the e.Item at the end of the DataBind and the good value is there. What can happen after onDataBind and before Render that can put an old value into the output? I am disabling ViewState for each textbox

Thanks
 
Well, I found out that the textbox is populated from Request.Form with old value!. So thats the problem. Now how do I prevent that?
 
again I'm not fully following how the user is interacting with the GUI, but this has been my experience with a gridview.

1. to reload a grid set the datasource and bind each time.
2. if the row is in edit mode and you want to cancel, use the cancel command within the grid view
3. i have never had a "reset" feature on my grids,but I would imagine it would work like this
Reset = Cancel, Edit Same Index

if that's the case then maybe this would work
Code:
void ResetRow()
{
   int index =GridView.EditIndex;
   GridView.DataSource = GetData();
   GridView.EditIndex = index;
   GridView.DataBind();
}

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top