Search code examples
asp.netgridviewtemplatefield

Assign the value of a templatefield on gridview to variable


I know how to get value the of a templatefield inside a RowDataBound event:

Control ctrl = e.Row.FindControl("Drop_Responsaveis");  
DropDownList ddl = ctrl as DropDownList;
ddl.items.add(something);

But I needto get it's value on a button_Click event... How May I do that?

Solution by the @Siz S answer

foreach (GridViewRow gvr in GridView1.Rows)
   {
     string str = ""
     Control ctrl = gvr.FindControl("Drop_Responsaveis");
     if (ctrl != null)
        {
           DropDownList ddl = ctrl as DropDownList;
           str= ddl.SelectedItem.ToString();
        }
    }

Solution

  • you can get gridview TemplateField controls as

    foreach (GridViewRow row in yourGrid.Rows)
    {
         Control ctrl = row.FindControl("Drop_Responsaveis");
         DropDownList ddl = ctrl as DropDownList;
         ddl.items.add(something);
     }