Set selected value or text for DropDownList in edit mode of gridview asp.net

Anh Hoang picture Anh Hoang · Jun 25, 2013 · Viewed 9.6k times · Source

In a gridview, to display data in view mode, I use a label.

In Edit mode I have a dropdownlist. So, How can I set text in that label as selected value for dropdownlist when gridview is in edit mode?

Here is my code in aspx page:

<Columns>             
<asp:BoundField DataField="id" HeaderText="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="Zone Name">
<HeaderStyle Width="220px"></HeaderStyle>
<ItemTemplate>
<asp:Label ID="lbDisplayName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>

<EditItemTemplate>
<asp:DropDownList ID="ddlName" runat="server" CssClass="customddlZoneName">
<asp:ListItem Value="">--Select Zone Name--</asp:ListItem>
<asp:ListItem Value="Value1">Text 1</asp:ListItem>
<asp:ListItem Value="Value2">Text 2</asp:ListItem>
<asp:ListItem Value="Value3">Text 3</asp:ListItem>
<asp:ListItem Value="Value4">Text 4</asp:ListItem>
<asp:ListItem Value="Value5">Text 5</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlInsertName" runat="server">
<asp:ListItem Value="">--Select Zone Name--</asp:ListItem>
<asp:ListItem Value="Value 1">Text 1</asp:ListItem>
<asp:ListItem Value="Value 2">Text 2</asp:ListItem>
<asp:ListItem Value="Value 3">Text 3</asp:ListItem>
<asp:ListItem Value="Value 4">Text 4</asp:ListItem>
<asp:ListItem Value="Value 5">Text 5</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

Answer

Anh Hoang picture Anh Hoang · Aug 15, 2013

I mean when I put my grid view in Edit mode, I don't want my Dropdownlist show "--Select Zone Name--". I want it show "text 1",2,3 or 4...which is displaying in my Label in View mode. And you can do this in Gridview_RowEditing event. See the code below:

protected void Gridview_RowEditing(object sender, GridViewEditEventArgs e)
{
    Label lbDisplayName = (Label)Gridview.Rows[e.NewEditIndex].FindControl("lbDisplayName");
    string name = lbDisplayName.Text;

    GridViewRow gvr = Gridview.Rows[e.NewEditIndex];
    var dr = (DropDownList)gvr.FindControl("ddlName");
    dr.SelectedItem.Text = name;
}