【问题标题】:ASP.NET Gridview - Checkbox - Select multiple rows and get recordsASP.NET Gridview - 复选框 - 选择多行并获取记录
【发布时间】:2010-12-09 00:05:46
【问题描述】:

我在某些列前面创建了一个带有复选框的网格视图。我需要获取用户正在选择的数据并构建一个 xml 文件。

我想不通。有人可以在 C# 中帮助我吗?

这是我目前的代码。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="ObjectDataSource1"  AllowPaging="True" BackColor="#DEBA84" BorderColor="#DEBA84" 
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />

<Columns>       

<asp:TemplateField>
<HeaderStyle HorizontalAlign="left" />
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" ToolTip="Click here to select/deselect all rows"
runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Service Point">
<ItemTemplate>                  
<%# Eval("SERVICEPOINTID")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<%# Eval("STARTTIME")%>
</ItemTemplate>                 
</asp:TemplateField>

谢谢,

史蒂夫

【问题讨论】:

  • 这篇文章可能会有所帮助 - Checking All Checkboxes in a GridView Using jQuery
  • 您能发布到目前为止您尝试过的代码隐藏吗?
  • 我没有发布它,因为我确信它是错误的并且它不起作用。 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //检查数据行 if (e.Row.RowType == DataControlRowType.DataRow) { //通过ID找到复选框控件并设置。 ((CheckBox)e.Row.FindControl("chkSelect")).Checked = IsItemChecked(((DataRowView)e.Row.DataItem)[0]); } }

标签: c# asp.net gridview


【解决方案1】:

您可以使用以下代码为选中的行一一获取值。

foreach (GridViewRow rowItem in GridView1.Rows)
  {
     var chk = (CheckBox)(rowItem.Cells[0].FindControl("chkSelectAll"));

     // chk.checked will access the checkbox state on button click event
     if (chk.Checked)
     {
         //get required values here
     }
  }

【讨论】:

    【解决方案2】:
    ForEach(GridViewRow row in MyGridView.Rows)
    {
      if (row.RowType == DataControlRowType.DataRow) //avoid header/footer rows.
      {
        var myCheckBox = (CheckBox)row.FindControl("chkSelect");
        //myCheckBox.Checked tells you if it's checked or not, yay!
        var myPrimaryKey = (GuidOrIntOrSomething)MyGridView.DataKeys[row.RowIndex].Value;
        //now you have your Key and the checkbox for whether the user has checked it 
        //and you can do your update/insert/delete/whatever against the DB.
      }
    }
    

    您确实应该处理使用 Check All 直接检查所有框所需的令人痛苦的 javascript。用户在点击回发时会收到回发,这是非常违反直觉和令人沮丧的。

    【讨论】:

      猜你喜欢
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多