C# getting selected value from dropdownlist in gridview asp net

人盡茶涼 提交于 2019-11-30 23:46:38

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;
}
user1666231

I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.

protected void dropDownLoad(object sender, EventArgs e)
{
    DropDownList dropDown = sender as DropDownList;
    if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
    { 
        // Your Code to populate table
    }
}

You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place

this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,

 <asp:TemplateField HeaderText="duty" SortExpression="duty">
                                       <EditItemTemplate>
                                      <asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
                                    </EditItemTemplate>
                                      <ItemTemplate>
                                           <asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
                                        <asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist" 
                                          OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false" 
                                           >
                                        </asp:DropDownList>
                                    </ItemTemplate>


                                        <HeaderStyle Width="5%" />
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!