Search code examples
c#asp.netaspxgridview

reading values from gridview template field in asp.net


Here is a code of template field in gridview . i want to get value of this field in string using c# code.

<asp:TemplateField HeaderText="Status" SortExpression="Status">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Status") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList2" runat="server">
                                    <asp:ListItem Value="P"></asp:ListItem>
                                    <asp:ListItem Value="L"></asp:ListItem>
                                    <asp:ListItem Value="A"></asp:ListItem>
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>

i tried the following code but its not working . here is my code for reading value.

 string str = gridview1.Rows[0].Cells[0].Text.ToString();

but its returning empty string. how can I get selected value.


Solution

  • You can't find the dropdown selected value like this. You need to find the control first using FindControl method:-

    DropDownList DropDownList2 =  (DropDownList)gridview1.Rows[0].Cells[0]
                                                         .FindControl("DropDownList2");
    string str = DropDownList2.SelectedValue;