views:

214

answers:

3

Using ASP.NET 3.5 ListView control.

I would like to capture the value of my table id from the currently edited row of a ListView.

A ItemEditing event has been added to the ListView. The only value available in this event is e.NewItemIndex. This returns 0 if the first row of the current page of the ListView is being edited.

How do I convert this 0 into the actual table id (label control value)?

I have tried:

table_id = Convert.ToString(ListView1.Items[e.NewEditIndex].FindControl("table_idLabel1"));
+1  A: 

Can you use the DataKeyNames property instead of a label? Set the property to the name of the database field that is the key for the table, then do something like this:

table_id = ListView1.DataKeys[e.NewEditIndex].Value.ToString();
Matthew Jones
Thanks!Nothing more frustrating then not knowing what to look for...
John M
Just don't start adding everything into the DataKeys. IDs are a good thing to put in there, but remember that datakays are stored in the viewstate.
Chris
A: 

Use FindControlRecursive (from http://www.codinghorror.com/blog/archives/000307.html). The problem with FindControl is that it only search one layer deep.

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
}
Chris
A: 

Are you sure table_idLabel1 is the correct id?

Also, you may need to look recursively as in Chris's answer. Plus, it looks like your casting the control to a string. You probably want the ID property and not the control itself.

Aaron Daniels