Dynamic gridview Asp.net with dropdownlists

I have a dynamic (allows you to add rows on the fly) gridview ASP, which has a drop-down list in one of its columns. I would like to take the action to enable / disable the text field in the column after depending on the selection in the drop-down list during data entry.

Any help would be greatly appreciated.

+4
source share
2 answers

You can do it easily with jQuery. With a little change, you can make it work the way you want it to.

First add the following to the <head> :

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $(".ddlClass").change(function () { var txt = $(this).closest("tr").find(".txtClass"); if ($(this).val() == 0) { txt.css("background", "#cccccc"); txt.attr("disabled", "disabled"); } else { txt.css("background", "#ffffff"); txt.attr("disabled",""); } }); }); 

Then create your gridview and add template columns for your text box and drop-down list. In the code below, note that the "ddlClass" class was assigned to the drop-down list, and the "txtClass" class was provided to the text box. You can change them as you wish.

 <asp:gridview runat="server" ID="gvw" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="field1" /> <asp:BoundField DataField="field2" /> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:TextBox runat="server" ID="txtName" CssClass="txtClass"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <select class="ddlClass"> <option value="1">Enabled</option> <option value="0">Disabled</option> </select> </ItemTemplate> </asp:TemplateField> </Columns> </asp:gridview> 

The .ready function attaches a click event to each drop-down list with the class "ddlClass". When changing, the code will find a text field with the class "txtClass" on the same line as the drop-down list, and then enable / disable accordingly.

+3
source

Well, you can use Javascript if you are familiar with this. I recommend using jQuery from the query language to translate through the DOM.

But if you are not familiar with Javascript, I recommend adding SelectionChangedEvent to a DropDownList, and then to the code for your page in the SelectionChangedEvent handler: Put the sender object in DropDownList, and then get the parent object of this object, which will be GridViewRow.

With this GridViewRow, you can use the FindControl method to get a link to a TextBox on the same line, and then you can enable or disable it.

If you don’t like the page refresh (post-back) every time they change the selection in the drop-down list, then wrap your grid in the UpdatePanel.

Let me know if it’s not easy for you, and I will send the code to one of the above solutions. Just let me know who you like best.

+1
source

Source: https://habr.com/ru/post/1345709/


All Articles