GridView Dynamic Button Frustrations
Today I spent 8 hours trying to figure this one out. I was using a CommandField control with ShowDeleteButton="true" in a GridView to handle deletion of records from a database table. Under certain circumstances, it caused a runtime exception. The only fix was to dynamically add the button to a TemplateColumn. I also had to add dynamic text to the button as well as remove the button from the TemplateColumn if a certain condition was met, so it was a good excuse to work on a fix. First, I tried a Button control. However, the OnClick event that I assigned to the Button control wouldn't fire. Next, I decided to try a ButtonField. I was getting close, but no cigar. I couldn’t get the ButtonField to do anything until I found the OnRowCreated event on MSDN and thought that that looks good so I'll add it to the GridView. Another dead end occurred. When the button was clicked this time, it would cause all the delete buttons to disappear. Also, this caused the message that I programmed to show when a condition was not met appeared in place of all the delete buttons. After retreating back to MSDN I found the OnRowDataBound event. After linking that event to the GridView, I could execute code when the delete button was clicked. But I hit yet another road block. After clicking any delete button, the records that did not meet the condition all of a sudden had buttons without any text, instead of the message that stated that there were no rows to delete. Also, records would still not delete. At this point many hours had past and I was rather frustrated at the disappearing/adding of buttons that didn't meet the condition and the delete buttons not deleting records. I reverted back to the OnRowCreated event and I went back to MSDN I and found the OnRowCommand event and linked it to the GridView. Finally, I could delete rows. However, I was still having the issue of delete buttons disappearing after clicking any delete button. Eventually, the idea to try to manually bind the GridView popped into my head. Once I did that it solved the button disappearing issue. However, this caused one side effect. I had a CommandField that was a SelectButton link. Clicking the link also caused the records to delete in the row it was clicked. So, I added a CommandName of Delete to the delete button so I could add a if statement to only delete records when the CommandName of Delete was passed. I got another exception because if the CommandName was Delete, it expects a DeleteCommand in the SqlDataSource. After 15 minutes of trying to fix this error, I finally realized that I had to rename the CommandName. Once I did that everything worked perfectly.
R




