?
Solved

GridView Edit mode from Code Behind

Posted on 2009-04-30
8
Medium Priority
?
5,741 Views
Last Modified: 2013-12-17
I have what apparently is a very difficult problem. I have a gridview control on my aspx page that is just the control and the columns entry, like so:
<asp:GridView runat="server" ID="gvTableList">
        <Columns>            
        </Columns>        
    </asp:GridView>

All of the columns I create in code behind in a function called populateGrid. The section is here:

public void populateGrid(string stable)
        {  
            fsTableList.Visible = true;
            SqlDataSource ds = new SqlDataSource();            
            try
            {
                //display current settings
                //pull connection string from web.config
                string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();

                ViewState["connString"] = connString;                                
               
                // Set datagrid column autogeneration to yes, then make it visible and enabled                
                gvTableList.AutoGenerateColumns = false;
                gvTableList.Visible = true;
                gvTableList.Enabled = true;
                gvTableList.AllowSorting = true;                
                gvTableList.AutoGenerateEditButton = true;
                gvTableList.AutoGenerateDeleteButton = true;
                               
                // Clear hyperlink column on a post back of the page
                if (Page.IsPostBack)
                {
                    gvTableList.Columns.Clear();
                }

                ViewState["stable"] = stable;
                               
                // Construct rest of grid based on which table is selected. Cant autogenerate because some fields
                // dont need to be visible.
                switch (stable)
                {                    
                    case "tblBackupMethods":
                        BoundField backupMethodID = new BoundField();
                        backupMethodID.DataField = "BackupMethodID";
                        backupMethodID.Visible = false;                        
                        BoundField backupMethodNameField = new BoundField();
                        backupMethodNameField.DataField = "BackupMethodName";                        
                        backupMethodNameField.SortExpression = "BackupMethodName";
                        backupMethodNameField.HeaderText = "Backup Method";                        
                        gvTableList.Columns.Add(backupMethodID);
                        gvTableList.Columns.Add(backupMethodNameField);
                        gvTableList.DataKeyNames = new string[] { "BackupMethodID" };
                       
                        Session["gvTableSort"] = stable;                        
                        break;

                    //Removed other case entries to simplicity, and they are all the same
                }
               
                // Set padding for display purposes, makes the grid look nicer.
                gvTableList.CellPadding = 5;
               
                // set up the datasource and bind it for the grid view to use.
                ds.ConnectionString = connString;
                ds.SelectCommand = query;
                ds.DataBind();

                // Setup the event calls for the grid.
                gvTableList.RowEditing += new GridViewEditEventHandler(gvTableList_RowEditing);
                gvTableList.RowDeleted += new GridViewDeletedEventHandler(gvTableList_RowDeleted);
                gvTableList.Sorting += new GridViewSortEventHandler(gvTableListSort);
                gvTableList.RowCancelingEdit += new GridViewCancelEditEventHandler(gvTableList_RowCancelingEdit);
                gvTableList.RowUpdating +=new GridViewUpdateEventHandler(gvTableList_RowUpdating);
               
                // set the datagrid datasource then bind it to display the data.                                
                gvTableList.DataSource = ds;
                gvTableList.DataBind();
            }
            finally
            {
               
            }
        }

It populates the grid fine, and when you click the edit button that also works. It puts a textbox appear.

void gvTableList_RowEditing(object sender, GridViewEditEventArgs e)
        {            
            //For the moment assume it's the backup method table
            gvTableList.EditIndex = e.NewEditIndex;
            gvTableList.DataBind();
        }

My problem is when you click the update button after changing the data in the textbox that appears when you click edit. I'm getting the value of the primary key value with datakeynames (you can see that in the case statement above). The updating function is here:

protected void gvTableList_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if(Page.IsValid)
            {
                // Get the table that was edited            
                switch (ViewState["stable"].ToString())
                {
case "tblBackupMethods":
                        int backupMethodID = Convert.ToInt32(gvTableList.DataKeys[e.RowIndex].Value);
                        string backupMethodName = ((TextBox)(gvTableList.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
                        DCBackupMethod backupmethod = new DCBackupMethod(backupMethodID);
                        string oldBackupMethodName = backupmethod.BackupMethodName;
                        backupmethod.BackupMethodName = backupMethodName;
                        if (backupmethod.BackupMethodName != backupMethodName)
                        {
                            backupmethod.Save();
                        }
                        (Utility.GetSystemAuditLogEntry("Backup Method Operations", backupmethod.BackupMethodName, String.Format("Backup Method '" + backupmethod.BackupMethodName + "' was modified to {0} from {1}", backupmethod.BackupMethodName, oldBackupMethodName))).Save();
                        gvTableList.DataBind();                        
                        break;

The int backupMethodID is pulling the correct data, but the string value can't pull the value of the textbox. I can't figure out how to do a FindControl on it since it is all a dynmically created control.
int backupMethodID = Convert.ToInt32(gvTableList.DataKeys[e.RowIndex].Value);
string backupMethodName = ((TextBox)(gvTableList.Rows[e.RowIndex].Cells[1].Controls[0])).Text;

So my question and problem is how to get the value of the textbox when the row is put into edit mode. I've been fighting this for a week and I've asked on another forum for .net and no one there apparently knows how to do this in code behind, so I'm hoping somewhere here does. Thanks!
0
Comment
Question by:smagnus1
  • 5
  • 3
8 Comments
 
LVL 16

Expert Comment

by:Walter Ritzel
ID: 24270003
Replace this line :
 string backupMethodName = ((TextBox)(gvTableList.Rows[e.RowIndex].Cells[1].Controls[0])).Text;

by those:
TextBox tb1 = (TextBox)e.Rows[e.RowIndex].Cells.FindControl(<control name>);
string backupMethodName = tb1.Text;
0
 
LVL 16

Expert Comment

by:Walter Ritzel
ID: 24270013
Fixing the code provided:
Replace this line :
 string backupMethodName = ((TextBox)(gvTableList.Rows[e.RowIndex].Cells[1].Controls[0])).Text;

by those:
TextBox tb1 = (TextBox)e.Row.Cells[column index].FindControl(<control name>);
string backupMethodName = tb1.Text;
0
 

Author Comment

by:smagnus1
ID: 24272128
wpcortes, I've tried to do that, but since I'm doing all of this in code behind how do you find a control that you can't assign a value to ID?
0
Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

 

Author Comment

by:smagnus1
ID: 24272754
If you look at this part of the code, these are the columns that appear in the grid when the page is rendered.
case "tblBackupMethods":
                        BoundField backupMethodID = new BoundField();
                        backupMethodID.DataField = "BackupMethodID";
                        backupMethodID.Visible = false;                        
                        BoundField backupMethodNameField = new BoundField();
                        backupMethodNameField.DataField = "BackupMethodName";                        
                        backupMethodNameField.SortExpression = "BackupMethodName";
                        backupMethodNameField.HeaderText = "Backup Method";                        
                        gvTableList.Columns.Add(backupMethodID);
                        gvTableList.Columns.Add(backupMethodNameField);
                        gvTableList.DataKeyNames = new string[] { "BackupMethodID" };
                       
                        Session["gvTableSort"] = stable;                        
                        break;

Then when I put it into edit mode the textbox appears but I don't have any templates or itemtemplates set so I can't figure out a way to assign an ID to that box. Any ideas?
0
 
LVL 16

Expert Comment

by:Walter Ritzel
ID: 24274383
Let's change a little bit, then:

string backupMethodName = e.NewValues[<column index for the field you want>].ToString();

Let me if this was helpful or not.





0
 

Author Comment

by:smagnus1
ID: 24275016
When I debug that it says that the count is 0
0
 

Accepted Solution

by:
smagnus1 earned 0 total points
ID: 24276585
I figured out how to do it myself. I ended up having to implement TemplateFields in code behind and I was able to get the value that way.
0
 

Author Comment

by:smagnus1
ID: 24276589
Moderator, I'm not sure how to handle a question that I answer myself.
0

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question