gridview上的复选框事件?

时间:2009-01-20 12:09:48

标签: c# .net

我在Windows应用程序的gridview上有一个复选框列。有人点击复选框后我想要一个事件。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

以下是一个示例:

<%@ Page Language="C#" AutoEventWireup="true" %>

<script runat="server">
    public class Item
    {
        public string Name { get; set; }
        public bool Checked { get; set; }
    }

    protected void Changed(object sender, EventArgs e)
    {
        CheckBox checkBox = sender as CheckBox;
        Response.Write(checkBox.Checked.ToString());
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grid.DataSource = new[] 
            { 
                new Item() { Name="1", Checked = true },
                new Item() { Name="2", Checked = false } 
            };
            grid.DataBind();
        }
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="check" runat="server" Checked='<%# Eval("Checked") %>' OnCheckedChanged="Changed" AutoPostBack="true" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

答案 1 :(得分:2)

新答案,因为现在我知道它是Windows窗体

首先,您需要将行设置为可编辑,以便用户在chekbox中单击,以避免您在客户端单击某行的CELL时看到。

让我们说第一个Cell是复选框:

和第二部分文字......

我的Form1.cs代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dgv.DataSource = new testData[] {
            new testData{ CheckBox = true, Name = "One" },
            new testData{ CheckBox = true, Name = "Two" },
            new testData{ CheckBox = false, Name = "Three" },
            new testData{ CheckBox = false, Name = "Four" }            
        };
    }

    private void dgv_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.ColumnIndex == 0) // It's the Checkbox Column
        {
            DataGridViewRow dgvr = dgv.Rows[e.RowIndex];
            MessageBox.Show(String.Format("Row {0} was cliked ({1})", (e.RowIndex + 1).ToString(), 
                dgvr.Cells[1].Value));
        }
    }
}

public class testData
{
    public Boolean CheckBox { get; set; }
    public String Name { get; set; }
}

设计...只需将DataGridView组件拖到窗体中,名为 dgv ,然后在事件中双击事件 CellMouseClick