accessing dynamic gridview controls

Last post 05-24-2008 10:54 AM by seeriustech. 9 replies.

Sort Posts:

  • accessing dynamic gridview controls

    04-16-2008, 9:14 PM
    • Loading...
    • seeriustech
    • Joined on 04-16-2008, 8:24 PM
    • Posts 7

    I have a grid sitting on the aspx with the autogenerated columns set to true.  I set the datasource to a datatable via code.  In the rowdatabound, for the row being edited, I hide the autogenerated textboxes and add my own controls to the cells.  This all works ok.  When the user clicks the update link, I'm trying to get access to the controls in rowupdating but they are not in the grid anywhere (at least I can't find them), but the textboxes are there.

    I assume all the columns are boundfields since they are autogenerated using the datatable.  I've seen that you are supposed to use templatefields when wanting to use your own controls but since I did not add the columns manually I was trying to find a work around.  I absolutely can't declare columns in the aspx since my data is not simplistic (ie I don't know how many columns need to be generated).

    Is this something to do with the viewstate?  Is the original setup of the grid in the viewstate but the added controls are not?  If so, how do I get my controls in the viewstate for the grid?

    Or are my controls being overwritten in an event occurring before rowupdating?  I couldn't find the order of events to play around with them.  But if I could even read the values of the controls prior to the rowupdating event and save them in a page variable, that would be a place to start.

    Any help is greatly appreciated! 

    *** Code Sample *** 

        protected void grid1_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
             if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((grid1.EditIndex != -1) && (e.Row.RowIndex == grid1.EditIndex))
                {
                    TextBox txbtemp;
                            //cycle through editable cells, add custom control, set custom control value, remove textbox
                            for (int icellidx = 0; icellidx < e.Row.Cells.Count; icellidx++)
                            {
                                CheckBox mycontrol = new CheckBox();
                                mycontrol.ID = "chk" + icellidx.ToString();
                                txbtemp = (TextBox)e.Row.Cells[icellidx].Controls[0];
                                if (txbtemp.Text == "1")
                                {
                                    mycontrol.Checked = true;
                                }
                                else
                                {
                                    mycontrol.Checked = false;
                                }
                                e.Row.Cells[icellidx].Controls.Add(mycontrol);

                                e.Row.Cells[icellidx].Controls[0].Visible = false;
                            }
                }
            }
        }

        protected void grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            for (int icolidx = 0; icolidx < grid1.Rows[e.RowIndex].Cells.Count; icolidx++)
            {
                        //This next line works which I would expect even though the control is supposedly hidden
                        //TextBox mytxb = grid1.Rows[e.RowIndex].Cells[icolidx].Controls[0] as TextBox;

                      //This doesn't work.  The cells only contain the textbox control for some reason so I get an out of range error.
                        CheckBox mychk = grid1.Rows[e.RowIndex].Cells[icolidx].Controls[1] as CheckBox;
            }
            //Reset the edit index.
            grid1.EditIndex = -1;

            //rebind grid
            grid1.Bind();
        }
     

    Filed under: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
  • Re: accessing dynamic gridview controls

    04-17-2008, 9:21 AM
    • Loading...
    • DiscernIT
    • Joined on 05-18-2005, 11:58 AM
    • UK
    • Posts 244

    Are you rebinding the gridview on postback? :- 

    when the user clicks update, the page will post back.. and your rowupdating method will run. but before that the code where you initially bind the data to the gridview will run unless you skip it by checking for postback using Page.IsPostback. If this is happening then the gridview will be reset without your injected checkbox.

  • Re: accessing dynamic gridview controls

    04-17-2008, 10:28 AM
    • Loading...
    • seeriustech
    • Joined on 04-16-2008, 8:24 PM
    • Posts 7

    Thanks for replying :)  No, I'm not rebinding prior to rowupdating being run.  See page_load below.  I also put in a static test for the cell I select (row = 4, col = 4).  I made a watch for the cell controls and it only shows the textbox.  My controls are gone.  After further research it seems any dynamic controls must be recreated everytime, which I do, but that means they are definitely being wiped out somewhere.  So that means I would have to figure out how to grab their values before that happens.  Or I've also been trying to look at the viewstate to see if I can get the control to persist.  I saw somewhere that CreateChildControl may help but couldn't figure out how for the gridview.  Again, any help is greatly appreciated!

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                    DataTable dt = getdatatable();  // getdatatable is one of my functions
                    grid1.DataSource = dt;
                    grid1.Bind();
            }
            if (grid1 != null)
            {
                        if (grid1.Rows[4].Cells[4].Controls.Count > 0) // count is only 1 when user clicks update link but I'm expecting 2
                        {
                            TextBox mytxb = (TextBox)grid1.Rows[4].Cells[4].Controls[0];  // this works
                            CheckBox mychk = (CheckBox)grid1.Rows[4].Cells[4].Controls[1];  // doesn't work because control doesn't exist at this point
                        }
            }
        }

  • Re: accessing dynamic gridview controls

    04-17-2008, 11:05 AM
    • Loading...
    • DiscernIT
    • Joined on 05-18-2005, 11:58 AM
    • UK
    • Posts 244

    boolean (bit) columns are should get auto-displayed in a gridview as checkboxes - then you wouldn't have to be doing this anyway... What datatype is the 'offending' column..

    I've generally found the automatic gridview columns of limited use becuase you end up doing more work in the end (as you're finding) - it's a tradeoff you get for having the convenience of the autocolumns. I'd normally find an alternative way of doing it.

  • Re: accessing dynamic gridview controls

    04-17-2008, 12:39 PM
    • Loading...
    • seeriustech
    • Joined on 04-16-2008, 8:24 PM
    • Posts 7

    Yep, I know, I had other controls I wanted to play with.  I was just using the checkbox as an example but probably should have chosen something not handled natively.  And I agree, auto columns are a little bit of a pain.  Worse case I was going to build the whole grid in code and use templatefields.  But I found a solution and I can kick myself for not thinking of it sooner.  Sometimes we forget the basics.  I can get the value out of the Request.Form.  So I'm going to "close" this thread.  Thanks again for replying!

  • Re: accessing dynamic gridview controls

    04-17-2008, 7:10 PM
    • Loading...
    • seeriustech
    • Joined on 04-16-2008, 8:24 PM
    • Posts 7

     Hmm, I may have spoke too soon.  Getting the value from Request.Form may work for simple controls where I just need the value but for more complex controls more work will be needed.  Such as for a file upload control.  It would be great if I could just use the control but if not I'll have to get the info out of the Request.Form and then use something like WebClient.UploadFile, HttpHostedFile, or something else (I have to look into it further).  Any suggestions for dealing with the File Upload or accessing any dynamically added gridview control in general would be greatly appreciated!

  • Re: accessing dynamic gridview controls

    04-18-2008, 4:04 AM

    Instead of this

    if (!Page.IsPostBack)
            {
                    DataTable dt = getdatatable();  // getdatatable is one of my functions
                    grid1.DataSource = dt;
                    grid1.Bind();
            }

    do

                   DataTable dt = getdatatable();  // getdatatable is one of my functions

                   grid1.DataSource = dt;
                    grid1.Bind();

     it shud work

     

    G.S
  • Re: accessing dynamic gridview controls

    04-18-2008, 9:00 AM
    Answer
    • Loading...
    • seeriustech
    • Joined on 04-16-2008, 8:24 PM
    • Posts 7

    Thanks for replying.  I didn't see why this would work but gave it a try anyway.  As expected, it wiped out any user changes.  As a reminder, I am able to get the controls to display whenever I need them.  It's getting access to them in the RowUpdating proc with the user entered values that's the problem.  

  • Re: accessing dynamic gridview controls

    05-23-2008, 1:20 PM
    • Loading...
    • digioz
    • Joined on 10-12-2005, 3:27 PM
    • Chicago, IL
    • Posts 76

    I had a similar issue, where posted data was getting overwritten by old data. Although your post was very helpful in solving my problem, it wasn't until I read this article that I figured out the exact cause of the issue:

     http://msdn.microsoft.com/en-us/library/aa478966.aspx

     In specific, the following section:

     

    ' Forgetting to Check for IsPostBack in the Page_Load Event
    ' One of the most common mistakes around is forgetting to check the page's 
    ' IsPostBack condition before databinding. For example, when the Datagrid is in 
    ' Edit mode, omitting this check will cause the edited values to be overwritten with 
    ' the original values from the data source. There is, however, at least one major 
    ' exception to this rule, see Enduring an Over-sized ViewState.
    
    ' The following is a typical Page_Load event which includes the IsPostBack checking. 
    ' BindGrid() is a routine that populates and sets the Datagrid's data source, and calls the DataBind() method.
    
    Sub Page_Load
      If Not IsPostBack Then 
        BindGrid()
      End If
    End Sub
    

     So basically its ok to re-populate the dataset after going in edit mode on page load, as long as you don't re-bind the grid.

     Pete

     

    DigiOz Multimedia
    http://www.digioz.com
  • Re: accessing dynamic gridview controls

    05-24-2008, 10:54 AM
    • Loading...
    • seeriustech
    • Joined on 04-16-2008, 8:24 PM
    • Posts 7

    We addressed the checking IsPostBack issue earlier in the thread.  That wasn't my problem.  But thanks for replying.  That article by Marcie (datagridgirl.com) is good and actually has a small section on dynamic controls but doesn't go into detail about accessing those controls before they are deconstructed.  As an fyi for anyone, she also has gridviewgirl.com.  And another great reference is Scott Mitchell's series of tutorials on this site (http://www.asp.net/learn/data-access/?lang=cs).  Scott has books and other sites as well.

Page 1 of 1 (10 items)
Microsoft Communities
Page view counter