Showing posts with label null. Show all posts
Showing posts with label null. Show all posts

Thursday, August 6, 2009

DataItem Dag-Nabbit!

Recently I was faced with the issue of trying to get multiple data columns from a DataGrid row during the event raised from a link button inside of a TemplatedColumn. When the link button was clicked, I was not able to access the selected item's DataItem. I had to find a work around. Microsoft does not allow access to the selected item's DataItem except during runtime using reflection. But, I needed to access the data item somehow so I created a workaround. Here is my original code:


                    
                        
                            
                                
                            
                        
                        other column 1
                        other column 2
                        other column 3
                     


protected void cmdUpdateContractID_Command(object sender, CommandEventArgs e)
        {
            DateTime RunDate = Convert.ToDateTime(e.CommandArgument.ToString());
            String RunSeq = e.CommandName.ToString();
        }

I wanted to be able to access the data from the other BoundColumns. So, I used an expression on my aspx page, and a custom method in the code behind to get around the DataItem lifecycle issue:


                    
                        
                            
                                
                            
                        
                        other column 1
                        other column 2
                        other column 3
                     


protected string GenerateArgString(object dataItem)
        {
            StringBuilder args = new StringBuilder();
            args.AppendFormat("{0}|", 
                 Convert.ToString(DataBinder.Eval(dataItem, "FIELD_1")));
            args.AppendFormat("{0}|", 
                 Convert.ToString(DataBinder.Eval(dataItem, "FIELD_2")));
            args.AppendFormat("{0}|", 
                 Convert.ToString(DataBinder.Eval(dataItem, "FIELD_3")));
            args.AppendFormat("{0}|", 
                 Convert.ToString(DataBinder.Eval(dataItem, "FIELD_4")));

            return args.ToString();
        }

You can see that I added the CommandArgument attribute to my Linkbutton, which in turn allowed me to generate a string of pipe delimited values from the selected item's DataItem. The expression calls the GenerateArgString method, which evaluates the DataItem using DataBinder.Eval method to retrieve information by column name.