如何在选中时向表头添加复选框列以全选?

huangapple go评论72阅读模式
英文:

How to add checkbox header column to check all when checked?

问题

I work on sp.net web forms . I face issue I can't add column checkbox to grid view as Header column.

so when header column checked then all rows checked on grid view

and when header column not checked then all rows not checked on grid view.

meaning all rows grid view will depend on column header checked or not.

so How to do that using jQuery or java script or CSS .

<div class="row">
    <div class="table-responsive">
        <asp:GridView ID="GridViewSearchData" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table" HeaderStyle-BackColor="#172b4d" ForeColor="White" OnDataBound="GridViewSearchData_OnDataBound" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="1">
            <Columns>
                    <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSel" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="BranchCode" HeaderText="BranchCode" />
                <asp:BoundField DataField="Status" HeaderText="Status" />
                <asp:BoundField DataField="OrderNo" HeaderText="OrderNo" ItemStyle-Width="120px" />
                <asp:BoundField DataField="OrderType" HeaderText="OrderType" />
                <asp:BoundField DataField="Printer_name" HeaderText="Printer_name" />
                <asp:BoundField DataField="EntredDatetime" HeaderText="EntredDatetime" />
                <asp:BoundField DataField="Id" HeaderText="Id" />
            </Columns>
        </asp:GridView>
    </div>
</div>

for grid view data source

protected void Search_Click(object sender, EventArgs e)
{
    DataTable dt;
    dt = busiObj.DisplayAllSearchData();
               
    if (dt != null && dt.Rows.Count > 0)
    {
        GridViewSearchData.DataSource = dt;
        GridViewSearchData.DataBind();
    }
}

image for expected result as red color first column

如何在选中时向表头添加复选框列以全选?


<details>
<summary>英文:</summary>

I work on sp.net web forms . I face issue I can&#39;t add column checkbox to grid view  as Header column .

so when header column checked then all rows checked on grid view 

and when header column not checked then all rows not checked on grid view .

meaning all rows grid view will depend on column header checked or not .

so How to do that using jQuery or java script or CSS .
```html
&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;table-responsive&quot;&gt;
        &lt;asp:GridView ID=&quot;GridViewSearchData&quot; runat=&quot;server&quot;  AutoGenerateColumns=&quot;False&quot;
        DataKeyNames=&quot;ID&quot; CssClass=&quot;table&quot; HeaderStyle-BackColor=&quot;#172b4d&quot; ForeColor=&quot;White&quot; OnDataBound=&quot;GridViewSearchData_OnDataBound&quot; AllowPaging=&quot;true&quot; OnPageIndexChanging=&quot;OnPageIndexChanging&quot; PageSize=&quot;1&quot;&gt;
            &lt;Columns&gt;
                    &lt;asp:TemplateField HeaderText=&quot;Select&quot; ItemStyle-HorizontalAlign=&quot;Center&quot;&gt;
                    &lt;ItemTemplate&gt;
                        &lt;asp:CheckBox ID=&quot;chkSel&quot; runat=&quot;server&quot; /&gt;
                    &lt;/ItemTemplate&gt;
                &lt;/asp:TemplateField&gt;
                &lt;asp:BoundField DataField=&quot;BranchCode&quot; HeaderText=&quot;BranchCode&quot; /&gt;
                &lt;asp:BoundField DataField=&quot;Status&quot; HeaderText=&quot;Status&quot; /&gt;
                &lt;asp:BoundField DataField=&quot;OrderNo&quot; HeaderText=&quot;OrderNo&quot; ItemStyle-Width=&quot;120px&quot; /&gt;
                &lt;asp:BoundField DataField=&quot;OrderType&quot; HeaderText=&quot;OrderType&quot; /&gt;
                &lt;asp:BoundField DataField=&quot;Printer_name&quot; HeaderText=&quot;Printer_name&quot; /&gt;
                &lt;asp:BoundField DataField=&quot;EntredDatetime&quot; HeaderText=&quot;EntredDatetime&quot; /&gt;                            
                &lt;asp:BoundField DataField=&quot;Id&quot; HeaderText=&quot;Id&quot; /&gt;
            &lt;/Columns&gt;
        &lt;/asp:GridView&gt;
    &lt;/div&gt;
&lt;/div&gt;

for grid view data source

protected void Search_Click(object sender, EventArgs e)
{
    DataTable dt;
    dt = busiObj.DisplayAllSearchData();
               
    if (dt != null &amp;&amp; dt.Rows.Count &gt; 0)
    {
        GridViewSearchData.DataSource = dt;
        GridViewSearchData.DataBind();
    }
}

image for expected result as red color first column

如何在选中时向表头添加复选框列以全选?

答案1

得分: 2

首先,如何将“任何”控件添加到标题中。

它的工作方式很像一个任何项模板。

开始一个“项模板”,然后在其中放置一个标题模板。

所以,现在我们有这个:

<h3>选择酒店</h3>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="ID" Width="50%" CssClass="table table-hover">
    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" />
        <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="Description" HeaderText="Description" />

        <asp:TemplateField
            ItemStyle-HorizontalAlign="Center"
            HeaderStyle-Width="70px">
            <HeaderTemplate>
                <div style="text-align: center">
                    All<br />
                    <asp:CheckBox ID="chkAll" runat="server"
                        OnCheckedChanged="chkAll_CheckedChanged"
                        AutoPostBack="true" />
                </div>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox ID="chkSel" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

然后,我们绑定了复选框的单击事件。所以,现在的代码是这样的:

protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
    CheckBox chkHeaderCheck = (CheckBox)sender;
    
    foreach (GridViewRow gRow in GridView1.Rows)
    {
        CheckBox ckRowSel = (CheckBox)gRow.FindControl("chkSel");
        ckRowSel.Checked = chkHeaderCheck.Checked;
    }
}

现在我们可以看到这样的效果:

如何在选中时向表头添加复选框列以全选?

所以,以上是非常简洁、非常容易的方法。

当然,我们也可以使用JavaScript在客户端100%执行此代码。

所以,现在我们的按钮(标题)没有服务器端的点击事件,也没有后台回发。

因此,现在的代码如下:

<asp:TemplateField
    ItemStyle-HorizontalAlign="Center"
    HeaderStyle-Width="70px">
    <HeaderTemplate>
        <div style="text-align: center">
            All<br />
            <asp:CheckBox ID="chkHeader" runat="server" 
                onclick="myheadcheck(this)" />
        </div>
    </HeaderTemplate>
    <ItemTemplate>
        <asp:CheckBox ID="chkSel" runat="server" />
    </ItemTemplate>
</asp:TemplateField>

JavaScript代码如下(使用jQuery):

<script>
    function myheadcheck(btn) {

        // 获取选中的一个复选框,是选中还是未选中?
        var bolChecked = $(btn).is(':checked');

        // 现在设置所有复选框
        MyTable = $('#<%= GridView1.ClientID %>')    // 选择并获取表格
        MyCheckBoxs = MyTable.find('input:checkbox') // 选择表格中的所有复选框
        MyCheckBoxs.each(function () {
            $(this).prop('checked', bolChecked);
        })
    }
</script>

现在的结果与之前一样,但没有服务器端的回发。

无论如何,注意标题模板的使用方式。

最后但同样重要的是:

不妨包括加载GridView的代码。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadGrid();
    }
}

protected void LoadGrid()
{
    using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
    {
        string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";
        using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
        {
            DataTable rstData = new DataTable();
            conn.Open();
            rstData.Load(cmdSQL.ExecuteReader());
            GridView1.DataSource = rstData;
            GridView1.DataBind();
        }
    }
}
英文:

First up, how to add "any" control to the header.

It works very much like say any item template.

Start a "item templte", and INSIDE that, drop in a header template.

So, we have this now:

&lt;h3&gt;Select Hotels&lt;/h3&gt;
&lt;asp:GridView ID=&quot;GridView1&quot; runat=&quot;server&quot; AutoGenerateColumns=&quot;False&quot;
    DataKeyNames=&quot;ID&quot; Width=&quot;50%&quot; CssClass=&quot;table table-hover&quot;&gt;
    &lt;Columns&gt;
        &lt;asp:BoundField DataField=&quot;FirstName&quot; HeaderText=&quot;FirstName&quot; /&gt;
        &lt;asp:BoundField DataField=&quot;LastName&quot; HeaderText=&quot;LastName&quot; /&gt;
        &lt;asp:BoundField DataField=&quot;HotelName&quot; HeaderText=&quot;HotelName&quot; /&gt;
        &lt;asp:BoundField DataField=&quot;City&quot; HeaderText=&quot;City&quot; /&gt;
        &lt;asp:BoundField DataField=&quot;Description&quot; HeaderText=&quot;Description&quot; /&gt;

        &lt;asp:TemplateField
            ItemStyle-HorizontalAlign=&quot;Center&quot;
            HeaderStyle-Width=&quot;70px&quot;&gt;
            &lt;HeaderTemplate&gt;
                &lt;div style=&quot;text-align: center&quot;&gt;
                    All&lt;br /&gt;
                    &lt;asp:CheckBox ID=&quot;chkAll&quot; runat=&quot;server&quot;
                        OnCheckedChanged=&quot;chkAll_CheckedChanged&quot;
                        AutoPostBack=&quot;true&quot; /&gt;
                &lt;/div&gt;
            &lt;/HeaderTemplate&gt;
            &lt;ItemTemplate&gt;
                &lt;asp:CheckBox ID=&quot;chkSel&quot; runat=&quot;server&quot; /&gt;
            &lt;/ItemTemplate&gt;
        &lt;/asp:TemplateField&gt;
    &lt;/Columns&gt;
&lt;/asp:GridView&gt;

And we wired up a click event for the check box. So, the code is now this:

    protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkHeaderCheck = (CheckBox)sender;
        
        foreach (GridViewRow gRow in GridView1.Rows)
        {
            CheckBox ckRowSel = (CheckBox)gRow.FindControl(&quot;chkSel&quot;);
            ckRowSel.Checked = chkHeaderCheck.Checked;
        }
    }

And now we get/see this:

如何在选中时向表头添加复选框列以全选?

So, above is real clean, VERY easy.

of course, we could do this code 100% client side with JavaScript.

So, now out button (header) has no server side click, nor a post-back.

So, this:

        &lt;asp:TemplateField
            ItemStyle-HorizontalAlign=&quot;Center&quot;
            HeaderStyle-Width=&quot;70px&quot;&gt;
            &lt;HeaderTemplate&gt;
                &lt;div style=&quot;text-align: center&quot;&gt;
                    All&lt;br /&gt;
                        &lt;asp:CheckBox ID=&quot;chkHeader&quot; runat=&quot;server&quot; 
                            onclick=&quot;myheadcheck(this)&quot; /&gt;
                &lt;/div&gt;
            &lt;/HeaderTemplate&gt;
            &lt;ItemTemplate&gt;
                &lt;asp:CheckBox ID=&quot;chkSel&quot; runat=&quot;server&quot; /&gt;
            &lt;/ItemTemplate&gt;
        &lt;/asp:TemplateField&gt;

And the js code is this: (jQuery)

  &lt;script&gt;

      function myheadcheck(btn) {

          // get the ONE check box, checked, or not???
          var bolChecked = $(btn).is(&#39;:checked&#39;)

          // now set all check boxes
          MyTable = $(&#39;#&lt;%= GridView1.ClientID %&gt;&#39;)    // select and get grid
          MyCheckBoxs = MyTable.find(&#39;input:checkbox&#39;) // select all check boxes in grid
          MyCheckBoxs.each(function () {
              $(this).prop(&#39;checked&#39;, bolChecked)
          })
      }
  &lt;/script&gt;

And now the result is really the same, but no server side post-back.

However, either way? Note the use of the Header template -

And last but not least?

Might as well include the code to load the gv.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGrid();
        }
    }
    protected void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = &quot;SELECT * FROM tblHotelsA ORDER BY HotelName&quot;;
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                DataTable rstData = new DataTable();
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

答案2

得分: 0

以下是您要翻译的内容:

示例使用 jQuery:

<asp:GridView ID="GridViewSearchData" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table" HeaderStyle-BackColor="#172b4d" ForeColor="White" OnDataBound="GridViewSearchData_OnDataBound" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="1">
    <Columns>
        <asp:TemplateField HeaderText="Select All" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:CheckBox ID="chkSel" runat="server" CssClass="chkSelectRow" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="BranchCode" HeaderText="BranchCode" />
        <asp:BoundField DataField="Status" HeaderText="Status" />
        <asp:BoundField DataField="OrderNo" HeaderText="OrderNo" ItemStyle-Width="120px" />
        <asp:BoundField DataField="OrderType" HeaderText="OrderType" />
        <asp:BoundField DataField="Printer_name" HeaderText="Printer_name" />
        <asp:BoundField DataField="EntredDatetime" HeaderText="EntredDatetime" />
        <asp:BoundField DataField="Id" HeaderText="Id" />
    </Columns>
</asp:GridView>

JavaScript:

<script type="text/javascript">
$(document).ready(function () {
    // Add click event to header checkbox
    $(".chkSelectAll").click(function () {
        $(".chkSelectRow").prop('checked', $(this).prop('checked'));
    });

    // Add click event to row checkboxes
    $(".chkSelectRow").click(function () {
        if ($(".chkSelectRow:checked").length == $(".chkSelectRow").length) {
            $(".chkSelectAll").prop('checked', true);
        }
        else {
            $(".chkSelectAll").prop('checked', false);
        }
    });
});
</script>

protected void GridViewSearchData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        CheckBox chkSelectAll = (CheckBox)e.Row.FindControl("chkSelectAll");
        chkSelectAll.Attributes.Add("onclick", "jQuery('.chkSelectRow').prop('checked', this.checked);");
    }
}
英文:

example using jquery:

&lt;asp:GridView ID=&quot;GridViewSearchData&quot; runat=&quot;server&quot; AutoGenerateColumns=&quot;False&quot; DataKeyNames=&quot;ID&quot; CssClass=&quot;table&quot; HeaderStyle-BackColor=&quot;#172b4d&quot; ForeColor=&quot;White&quot; OnDataBound=&quot;GridViewSearchData_OnDataBound&quot; AllowPaging=&quot;true&quot; OnPageIndexChanging=&quot;OnPageIndexChanging&quot; PageSize=&quot;1&quot;&gt;
&lt;Columns&gt;
&lt;asp:TemplateField HeaderText=&quot;Select All&quot; ItemStyle-HorizontalAlign=&quot;Center&quot;&gt;
&lt;ItemTemplate&gt;
&lt;asp:CheckBox ID=&quot;chkSel&quot; runat=&quot;server&quot; CssClass=&quot;chkSelectRow&quot; /&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;asp:BoundField DataField=&quot;BranchCode&quot; HeaderText=&quot;BranchCode&quot; /&gt;
&lt;asp:BoundField DataField=&quot;Status&quot; HeaderText=&quot;Status&quot; /&gt;
&lt;asp:BoundField DataField=&quot;OrderNo&quot; HeaderText=&quot;OrderNo&quot; ItemStyle-Width=&quot;120px&quot; /&gt;
&lt;asp:BoundField DataField=&quot;OrderType&quot; HeaderText=&quot;OrderType&quot; /&gt;
&lt;asp:BoundField DataField=&quot;Printer_name&quot; HeaderText=&quot;Printer_name&quot; /&gt;
&lt;asp:BoundField DataField=&quot;EntredDatetime&quot; HeaderText=&quot;EntredDatetime&quot; /&gt;                            
&lt;asp:BoundField DataField=&quot;Id&quot; HeaderText=&quot;Id&quot; /&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;

JavaScript:

&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready(function () {
// Add click event to header checkbox
$(&quot;.chkSelectAll&quot;).click(function () {
$(&quot;.chkSelectRow&quot;).prop(&#39;checked&#39;, $(this).prop(&#39;checked&#39;));
});
// Add click event to row checkboxes
$(&quot;.chkSelectRow&quot;).click(function () {
if ($(&quot;.chkSelectRow:checked&quot;).length == $(&quot;.chkSelectRow&quot;).length) {
$(&quot;.chkSelectAll&quot;).prop(&#39;checked&#39;, true);
}
else {
$(&quot;.chkSelectAll&quot;).prop(&#39;checked&#39;, false);
}
});
});

</script>

protected void GridViewSearchData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox chkSelectAll = (CheckBox)e.Row.FindControl(&quot;chkSelectAll&quot;);
chkSelectAll.Attributes.Add(&quot;onclick&quot;, &quot;jQuery(&#39;.chkSelectRow&#39;).prop(&#39;checked&#39;, this.checked);&quot;);
}
}

huangapple
  • 本文由 发表于 2023年3月1日 13:25:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定