Asp.net 如何在 GridView 的文本框中分配选定的下拉文本

How Assigning selected text of dropdown in textbox of GridView in Asp.net

如果您想将下拉列表的选定文本值分配给同一行的另一个单元格中存在的文本框。您可以使用 jQuery 来实现相同的目的。请参考以下示例。

$(function() {  
$("[id*=ddlCurrency]").change(function() {  
var ddy = $(this).find('option').filter(':selected').text();  
var row = $(this).closest("tr");  
 $("[id*=txtProjectCurrencyName]", row).val(ddy);  
});  

});

除非您在其他地方出现脚本错误,否则您的代码可以正常工作。

这是我的测试 -

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="DemoWebForm.GridViewDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Id" />
                <asp:BoundField DataField="Name" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:DropDownList runat="server" ID="ddlCurrency">
                            <asp:ListItem Text="" Value="" />
                            <asp:ListItem Text="USD" Value="USD" />
                            <asp:ListItem Text="EUR" Value="EUR" />
                            <asp:ListItem Text="GBP" Value="GBP" />
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox runat="server" ID="txtProjectCurrencyName" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script>
            $(function () {
                $("[id*=ddlCurrency]").change(function () {
                    var ddy = $(this).find('option').filter(':selected').text();
                    var row = $(this).closest("tr");
                    $("[id*=txtProjectCurrencyName]", row).val(ddy);
                });
            });
        </script>
    </form>
</body>
</html>

代码隐藏

using System;
using System.Collections.Generic;

namespace DemoWebForm
{
    public partial class GridViewDemo : System.Web.UI.Page
    {
        public class Currency
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public static IList<Currency> Currencies = new List<Currency>
        {
            new Currency {Id = 1, Name = "One"},
            new Currency {Id = 2, Name = "Two"},
            new Currency {Id = 3, Name = "Three"}
        };

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridView1.DataSource = Currencies;
                GridView1.DataBind();
            }
        }
    }
}