Select2 plugin inside Gridview works with only last row of grid in asp.net

扶醉桌前 提交于 2021-02-11 05:02:00

问题


HEADER used select2-4.0.13 and bootstrap v4.4.1 in asp.net webpage

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <link href="Styles/Bootstrap v4.4.1/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="Styles/Select2-4.0.13/select2.min.css" rel="stylesheet" type="text/css" />
    <link href="Styles/Select2-4.0.13/select2-bootstrap4.min.css" rel="stylesheet" type="text/css" />
</asp:Content>

ASPX Page created gridview with 3 columns where first column contains dropdownlist with select2 plug in, but select2 works with only last row for gridview, for other rows it displays normal dropdown list

<asp:GridView ID="grdPackingSlipItem" runat="server" AllowPaging="false" AutoGenerateColumns="False"
    CssClass="table-xs table-responsive table-striped table-bordered table-hover p-1"
    EmptyDataText="No rows for the selection criteria." EnableTheming="False" OnRowDataBound="grdPackingSlipItem_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Sl.No" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="50" HeaderStyle-Font-Bold="false">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Item Name" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"
            ItemStyle-Width="220" HeaderStyle-Font-Bold="false" ControlStyle-Width="100%">
            <ItemTemplate>
                <asp:DropDownList runat="server" ID="grdtxtItemName" ClientIDMode="Static" data-width="100%"
                    CssClass="select2-single input-sm w-100" data-placeholder="Item Name....." AppendDataBoundItems="true">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Pcs" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
            ItemStyle-Width="100" HeaderStyle-Font-Bold="false" ControlStyle-Width="100%">
            <ItemTemplate>
                <asp:TextBox ID="grdtxtPcs" runat="server" ClientIDMode="Static" onkeypress="return isIntegerKey(event);"
                    OnPaste="return false" MaxLength="10" BorderStyle="Solid" BorderColor="WhiteSmoke"
                    Text='<%#DataBinder.Eval(Container.DataItem, "QUANTITY")%>'>
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <HeaderStyle Font-Names="Tahoma" Font-Size="9pt" BackColor="#5D7B9D" Font-Bold="false"
        ForeColor="White" HorizontalAlign="Center" />
    <RowStyle Font-Names="Tahoma" Font-Size="10pt" ForeColor="Black" Height="30" />
    <PagerStyle CssClass="GridPager" />
</asp:GridView>

Script Section linked required scripts bootstrap4 and select2 scripts , initialised select2 for dropdownlist with ID ".select2-single"

<script src="Scripts/jquery-3.4.1/jquery-3.4.1.min.css" type="text/javascript"></script>
<script src="Scripts/Bootstrap v4.4.1/popper.min.js" type="text/javascript"></script>
<script src="Scripts/Bootstrap v4.4.1/bootstrap.min.js" type="text/javascript"></script>
<script src="Scripts/Bootstrap v4.4.1/bootstrap.bundle.min.js" type="text/javascript"></script>
<script src="Scripts/Select2-4.0.13/select2.full.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        initSelect2();
    });

    function pageLoad() {
        initSelect2();
    }

    function initSelect2() {
        $('.select2-single').select2({
            theme: 'bootstrap4',
            width: 'style',
            containerCssClass: ':all:',
            allowClear: true
        });
    }
</script>

Code Behind

loaded gridview with datatable in page load

private void LoadGridData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("RECORD_ID", typeof(int)));
    dt.Columns.Add(new DataColumn("PRODUCT_ID", typeof(int)));
    dt.Columns.Add(new DataColumn("PRODUCT_NAME", typeof(string)));
    dt.Columns.Add(new DataColumn("QUANTITY", typeof(int)));
    //empty row on if no record
    DataRow dtEmptyrow = dt.NewRow();
    dtEmptyrow["RECORD_ID"] = 1;
    dtEmptyrow["PRODUCT_ID"] = 1;
    dtEmptyrow["PRODUCT_NAME"] = "Apple";
    dtEmptyrow["QUANTITY"] = 100;
    dt.Rows.Add(dtEmptyrow);

    dtEmptyrow = dt.NewRow();
    dtEmptyrow["RECORD_ID"] = 2;
    dtEmptyrow["PRODUCT_ID"] = 5;
    dtEmptyrow["PRODUCT_NAME"] = "Oppo";
    dtEmptyrow["QUANTITY"] = 500;
    dt.Rows.Add(dtEmptyrow);

    dtEmptyrow = dt.NewRow();
    dtEmptyrow["RECORD_ID"] = 3;
    dtEmptyrow["PRODUCT_ID"] = 3;
    dtEmptyrow["PRODUCT_NAME"] = "Samsung";
    dtEmptyrow["QUANTITY"] = 300;
    dt.Rows.Add(dtEmptyrow);


    ViewState["PackingSlipItem"] = dt.Copy(); // original copy
    grdPackingSlipItem.DataSource = dt;
    grdPackingSlipItem.DataBind();
}

on gridview row databound bind list of items for dropdown list

protected void grdPackingSlipItem_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //onrowdatabound = true;
            DataTable oDataTableSubCategory = new DataTable();
            oDataTableSubCategory.Columns.Add(new DataColumn("PRODUCT_ID", typeof(int)));
            oDataTableSubCategory.Columns.Add(new DataColumn("PRODUCT_NAME", typeof(string)));

            //empty row on if no record
            DataRow dtEmptyrow = oDataTableSubCategory.NewRow();
            dtEmptyrow["PRODUCT_ID"] = 1;
            dtEmptyrow["PRODUCT_NAME"] = "Apple";
            oDataTableSubCategory.Rows.Add(dtEmptyrow);

            dtEmptyrow = oDataTableSubCategory.NewRow();
            dtEmptyrow["PRODUCT_ID"] = 2;
            dtEmptyrow["PRODUCT_NAME"] = "Microsoft";
            oDataTableSubCategory.Rows.Add(dtEmptyrow);

            dtEmptyrow = oDataTableSubCategory.NewRow();
            dtEmptyrow["PRODUCT_ID"] = 3;
            dtEmptyrow["PRODUCT_NAME"] = "Samsung";
            oDataTableSubCategory.Rows.Add(dtEmptyrow);

            dtEmptyrow = oDataTableSubCategory.NewRow();
            dtEmptyrow["PRODUCT_ID"] = 4;
            dtEmptyrow["PRODUCT_NAME"] = "Nokia";
            oDataTableSubCategory.Rows.Add(dtEmptyrow);

            dtEmptyrow = oDataTableSubCategory.NewRow();
            dtEmptyrow["PRODUCT_ID"] = 5;
            dtEmptyrow["PRODUCT_NAME"] = "Oppo";
            oDataTableSubCategory.Rows.Add(dtEmptyrow);

            DropDownList DropDownList1 = (e.Row.FindControl("grdtxtItemName") as DropDownList);
            DropDownList1.Items.Clear();
            DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
            //DropDownList1.SelectedIndex = 0;
            DropDownList1.DataSource = oDataTableSubCategory;
            DropDownList1.DataTextField = "PRODUCT_NAME";
            DropDownList1.DataValueField = "PRODUCT_ID";
            DropDownList1.DataBind();
            string selectedPRODUCTSUBCAT_ID = DataBinder.Eval(e.Row.DataItem, "PRODUCT_ID").ToString();
            string selectedPRODUCTSUBCAT_NAME = DataBinder.Eval(e.Row.DataItem, "PRODUCT_NAME").ToString();
            DropDownList1.Items.FindByText(selectedPRODUCTSUBCAT_NAME).Selected = true;
        }
    }
    catch (Exception ex)
    { }
}

works with last row only for other rows it display normal dropdownlist


回答1:


You are using ClientIDMode="Static" inside the GridView. This will result in muliple DropDownList and TextBox to have the same ID. If you look at the generated HTML, you will find that all the DropDownList have the ID grdtxtItemName.

But all elements, webforms or not should have a unique ID. Select2 binds based on ID and since they are all the same only the last one is functional. So remove the ClientIDMode.

<asp:DropDownList runat="server" ID="grdtxtItemName" data-width="100%"
    CssClass="select2-single input-sm w-100" data-placeholder="Item Name....." AppendDataBoundItems="true">
</asp:DropDownList>


来源:https://stackoverflow.com/questions/63787491/select2-plugin-inside-gridview-works-with-only-last-row-of-grid-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!