asp:GridView - 单击行中的任意位置时更改复选框状态

时间:2012-01-23 11:16:24

标签: c# asp.net gridview

我有一个网络应用程序并使用gridview来显示一些SQL数据。在GV中,我在第一列中有一个复选框。如标题中所示,我想在用户点击该行中的任意位置时选中该复选框。我怎样才能做到这一点。感谢。

这是我的GV;

<asp:GridView ID="myGV" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
            OnRowDataBound="myGV_OnRowDataBound">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="myCB" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />

我使用此代码在鼠标指针悬停时突出显示该行;

protected void myGV_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#D9ECFB'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
    }
}

编辑:

我将“OnSelectedIndexChanging”和“OnSelectedIndexChanged”添加到GridView,然后尝试了这个(由Ravi建议),但无法使其工作。

protected void myGV_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
    GridViewRow row = myGV.Rows[e.NewSelectedIndex];

    CheckBox chk = (CheckBox)myGV.FindControl("cbIzpis");

    if (chk.Checked == true)
    {
        chk.Checked = false;
    }
    else if (chk.Checked == false)
    {
        chk.Checked = true;
    }
}

protected void myGV_SelectedIndexChanged(Object sender, EventArgs e)
{
    GridViewRow row = nyGV.SelectedRow;
}

1 个答案:

答案 0 :(得分:2)

您可以使用GridView.SelectedRow属性,使用SelectedIndexChanged事件,Gridview Selected Row

 void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;
    MessageLabel.Text = "You selected " + row.Cells[2].Text + ".";

  }

  void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
  {

    // SelectedIndexChanging event occurs before the select operation in the GridView control, the
    // SelectedRow property cannot be used. Instead, use the Rows collection
    // and the NewSelectedIndex property of the e argument passed to this 
    // event handler.
    GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
    // here you can check the checkbox, by accessing it in template column using findControl method 
     CheckBox chk = (CheckBox) CustomersGridview.FindControl("chkboxID"); 
    chk.checked;    


    if (row.Cells[1].Text == "SomeCondition")
    {

      e.Cancel = true;
      MessageLabel.Text = "You cannot select " + row.Cells[2].Text + ".";

    }

  }