C# getting selected value from dropdownlist in gridview asp net

gogogo picture gogogo · Jun 24, 2012 · Viewed 36.6k times · Source

How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?

On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.

The code is below.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
    <Columns>
        <asp:TemplateField HeaderText="Entry">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Duty">
            <ItemTemplate>
                <asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

The code behind is below.

protected void ddl1_load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        Duty dy = new Duty();
        dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
        DropDownList ddl = (DropDownList)sender;
        ddl.DataSource = dt;
        ddl.DataTextField = "dutyid";
        ddl.DataValueField = "dutyid";
        ddl.DataBind();
        TextBox1.Text = ddl.SelectedValue;
    }
}

Answer

Coder picture Coder · Jun 24, 2012

You need to use SelectedIndexChanged handler to show selected value:

Markup:

<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>

Code-behind:

protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);   
    DropDownList duty= (DropDownList) gvr.FindControl("duty");
    TextBox1.Text = duty.SelectedItem.Value;
}