Get the Selected row of Gridview

百般思念 提交于 2020-01-03 16:54:39

问题


I have a Gridview.I placed checkbox on each row.By selecting the checkbox and clicking on delete button i should get all the selected row of that gridview in the codebehind.Please do help me...

<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" 
        BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
        CellSpacing="2" style="margin-left: 58px; margin-top: 13px" >
          <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
          <Columns>
              <asp:TemplateField>
                  <EditItemTemplate>
                      <asp:CheckBox ID="CheckBox1" runat="server" />
                  </EditItemTemplate>
                  <ItemTemplate>
                      <asp:CheckBox ID="CheckBox1" runat="server" />
                  </ItemTemplate>
              </asp:TemplateField>
          </Columns>

    </asp:GridView>
    <asp:Button ID="Delete" runat="server" Text="Button"  runat="server" 
        onclick="Delete_Click" />

codebehind

protected void Button1_Click(object sender, EventArgs e)
    {
        string valueForDB = DatabaseList.SelectedValue;
        Data obj = new Data();
        if (valueForDB == "virtualworkplace")
        {
            obj.getDocforVirtualwrkspace(valueForDB);
            GridView1.DataSource = obj.getDocforVirtualwrkspace(valueForDB);
            GridView1.DataBind();
        }
What to write here???
 protected void Delete_Click(object sender, EventArgs e)
    {
        }

回答1:


Try this

 private void DeleteRows()
 {
        foreach (GridViewRow row in gridView1.Rows)
        {
            HtmlInputCheckBox chk = (HtmlInputCheckBox) row.Cells[0].FindControl("selectedrowchk");
            if (chk != null && chk.Checked)
            {
                string id = gridView1.DataKeys[row.RowIndex].Value.ToString(); // get the record's ID of this row
                deleteRecord(id);
            }
        }

        //RefreshGrid();
    }

This code is assuming you set the DataKeyNames property of the GridView to store the primary key of each record. It is also assuming you are putting the checkbox in the first column




回答2:


to set datakeys use the datakeynames property from the gridview

 <asp:GridView AllowSorting="true" AutoGenerateColumns="false" AllowPaging="true" 
        PageSize="10" DataKeyNames="MembershipNo"  
        ID="grdvw_showdetails" runat="server" CellPadding="4" 


来源:https://stackoverflow.com/questions/12775253/get-the-selected-row-of-gridview

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