如何在Asp.net Gridview列中添加复选框的事件?

时间:2021-02-25 03:35:20

I have a gridview in asp where i have added first column as checkbox column.Now i want to select this column and get the id values of the row ..But I am not getting how to do it..

我在asp中有一个gridview,我在这里添加了第一列作为复选框列。现在,我要选择这个列并获取该行的id值。但是我不知道怎么做。

This is my Aspx code..

这是我的Aspx代码。

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
                    AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" 
                    BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" 
                    GridLines="None">
                    <AlternatingRowStyle BackColor="PaleGoldenrod" />
                    <Columns>
                     <asp:TemplateField>
                            <HeaderTemplate>
                                <asp:CheckBox ID="chkhdr" runat="server" />
                            </HeaderTemplate>
                          <ItemTemplate>
                                <asp:CheckBox ID="chkChild" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Username">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("col0") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Role(Admin)">
                            <ItemTemplate>
                                <asp:CheckBox ID="chkAdmin" runat="server" Checked='<%# Eval("col1") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Role(User)">
                            <ItemTemplate>
                                <asp:CheckBox ID="chkUser" runat="server" Checked='<%# Eval("col2") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Role(GeneralUser)">
                            <ItemTemplate>
                                <asp:CheckBox ID="chkgen" runat="server" Checked='<%# Eval("col3") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

And here is my code behind file...

这是我的文件后面的代码…

protected void BindGridviewData()
{

    var role = from MembershipUser u in Membership.GetAllUsers()
                select new
                {
                    User = u.UserName,
                    Role = string.Join(",", Roles.GetRolesForUser(u.UserName))
                };

    DataTable dTable = new DataTable();
    dTable.Columns.Add("col0", typeof(string));
    dTable.Columns.Add("col1", typeof(bool));
    dTable.Columns.Add("col2", typeof(bool));
    dTable.Columns.Add("col3", typeof(bool));
    foreach (MembershipUser u in Membership.GetAllUsers())
    {
        DataRow dRow = dTable.NewRow();
        dRow[0] = u.UserName;

        string[] roles = Roles.GetRolesForUser(u.UserName);
        dRow[1] = roles.Contains("Admin") ? true : false;
        dRow[2] = roles.Contains("DPAO User") ? true : false;
        dRow[3] = roles.Contains("GeneralUser") ? true : false;
        dTable.Rows.Add(dRow);
    }
    GridView1.DataSource = dTable;
    GridView1.DataBind();
}

Please Guys help me as i have no idea how to accomplish this ...Thanks in advance...

请帮我个忙,因为我不知道该怎么做……提前谢谢…

5 个解决方案

#1


1  

If you want Delete record by Button try this:

如果你想按按钮删除记录,试试这个:

Add a Button outside of gridview for Delete:

在gridview外添加一个按钮用于删除:

<asp:Button ID="cmdDelete" runat="server" onclick="cmdDelete_Click" Text="Delete" />

Code behind:

背后的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridviewData();
    }
}
protected void BindGridviewData()
{
    DataTable dTable = new DataTable();
    dTable.Columns.Add("col0", typeof(string));
    dTable.Columns.Add("col1", typeof(bool));
    dTable.Columns.Add("col2", typeof(bool));
    dTable.Columns.Add("col3", typeof(bool));
    foreach (MembershipUser u in Membership.GetAllUsers())
    {
        DataRow dRow = dTable.NewRow();
        dRow[0] = u.UserName;
        string[] roles = Roles.GetRolesForUser(u.UserName);
        dRow[1] = roles.Contains("Admin") ? true : false;
        dRow[2] = roles.Contains("DPAO User") ? true : false;
        dRow[3] = roles.Contains("GeneralUser") ? true : false;
        dTable.Rows.Add(dRow);
    }
    GridView1.DataSource = dTable;
    GridView1.DataBind();
}
protected void cmdDelete_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)row.FindControl("chkChild");
        if (chk.Checked)
        {
            Label username = (Label)row.FindControl("Label1");
            Membership.DeleteUser(username.Text);
            BindGridviewData();
        }
    }
}

#2


6  

try this,

试试这个,

<asp:TemplateField HeaderText="View">
   <ItemTemplate>
      <asp:CheckBox ID="chkview" runat="server" AutoPostBack="true" OnCheckedChanged="chkview_CheckedChanged" />
   </ItemTemplate>
</asp:TemplateField>

add checkbox change event in aspx.cs page

在aspx中添加复选框更改事件。cs页面

protected void chkview_CheckedChanged(object sender, EventArgs e)
{
    GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
    int index = row.RowIndex;
    CheckBox cb1 = (CheckBox)Gridview.Rows[index].FindControl("chkview");
    string yourvalue = cb1.Text;
    //here you can find your control and get value(Id).

}

#3


0  

You can iterate through gridivew row collection and check whether it has been selected.

您可以遍历gridivew行集合并检查它是否已被选中。

Add selected row (or get ID in your case) and do further processing.

添加选定的行(或在您的示例中获得ID)并进行进一步处理。

Below URL may help you to get started:

以下网址可以帮助你开始:

http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx

http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx

#4


0  

Use the OnCheckedChanged event

使用OnCheckedChanged事件

<ItemTemplate>
  <asp:CheckBox ID="chkgen" runat="server" Checked='<%# Eval("col3") %>'  
        OnCheckedChanged="chkgen_OnCheckedChanged"/>
</ItemTemplate>

CS:

CS:

protected void chkgen_OnCheckedChanged(object sender, EventArgs e)
{
      int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
      CheckBox cb = (CheckBox)gridView.Rows[selRowIndex].FindControl("chkgen");

      if (cb.Checked)
      {
             //Perform your logic
      }
}

#5


0  

 protected void GetFillDropdown()
    {
        string consString = ConfigurationManager.ConnectionStrings["SheetalAcademy"].ConnectionString;
        SqlConnection conn = new SqlConnection(consString);

        int EID = Convert.ToInt32(Session["EmailID"].ToString());
        SqlCommand cmd = new SqlCommand("Select id,Course_Name from tbl_Courses where EID='" + EID + "' and Active='True'", conn);
        conn.Open();
        ddCourseType.Items.Clear();
        ddCourseType.Items.Add("All");
        ddCourseType.AppendDataBoundItems = true;
        ddCourseType.DataSource = cmd.ExecuteReader();
        ddCourseType.DataTextField = "Course_Name";
        ddCourseType.DataValueField = "id";
        ddCourseType.DataBind();
        conn.Close();

    }

#1


1  

If you want Delete record by Button try this:

如果你想按按钮删除记录,试试这个:

Add a Button outside of gridview for Delete:

在gridview外添加一个按钮用于删除:

<asp:Button ID="cmdDelete" runat="server" onclick="cmdDelete_Click" Text="Delete" />

Code behind:

背后的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridviewData();
    }
}
protected void BindGridviewData()
{
    DataTable dTable = new DataTable();
    dTable.Columns.Add("col0", typeof(string));
    dTable.Columns.Add("col1", typeof(bool));
    dTable.Columns.Add("col2", typeof(bool));
    dTable.Columns.Add("col3", typeof(bool));
    foreach (MembershipUser u in Membership.GetAllUsers())
    {
        DataRow dRow = dTable.NewRow();
        dRow[0] = u.UserName;
        string[] roles = Roles.GetRolesForUser(u.UserName);
        dRow[1] = roles.Contains("Admin") ? true : false;
        dRow[2] = roles.Contains("DPAO User") ? true : false;
        dRow[3] = roles.Contains("GeneralUser") ? true : false;
        dTable.Rows.Add(dRow);
    }
    GridView1.DataSource = dTable;
    GridView1.DataBind();
}
protected void cmdDelete_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)row.FindControl("chkChild");
        if (chk.Checked)
        {
            Label username = (Label)row.FindControl("Label1");
            Membership.DeleteUser(username.Text);
            BindGridviewData();
        }
    }
}

#2


6  

try this,

试试这个,

<asp:TemplateField HeaderText="View">
   <ItemTemplate>
      <asp:CheckBox ID="chkview" runat="server" AutoPostBack="true" OnCheckedChanged="chkview_CheckedChanged" />
   </ItemTemplate>
</asp:TemplateField>

add checkbox change event in aspx.cs page

在aspx中添加复选框更改事件。cs页面

protected void chkview_CheckedChanged(object sender, EventArgs e)
{
    GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
    int index = row.RowIndex;
    CheckBox cb1 = (CheckBox)Gridview.Rows[index].FindControl("chkview");
    string yourvalue = cb1.Text;
    //here you can find your control and get value(Id).

}

#3


0  

You can iterate through gridivew row collection and check whether it has been selected.

您可以遍历gridivew行集合并检查它是否已被选中。

Add selected row (or get ID in your case) and do further processing.

添加选定的行(或在您的示例中获得ID)并进行进一步处理。

Below URL may help you to get started:

以下网址可以帮助你开始:

http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx

http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx

#4


0  

Use the OnCheckedChanged event

使用OnCheckedChanged事件

<ItemTemplate>
  <asp:CheckBox ID="chkgen" runat="server" Checked='<%# Eval("col3") %>'  
        OnCheckedChanged="chkgen_OnCheckedChanged"/>
</ItemTemplate>

CS:

CS:

protected void chkgen_OnCheckedChanged(object sender, EventArgs e)
{
      int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
      CheckBox cb = (CheckBox)gridView.Rows[selRowIndex].FindControl("chkgen");

      if (cb.Checked)
      {
             //Perform your logic
      }
}

#5


0  

 protected void GetFillDropdown()
    {
        string consString = ConfigurationManager.ConnectionStrings["SheetalAcademy"].ConnectionString;
        SqlConnection conn = new SqlConnection(consString);

        int EID = Convert.ToInt32(Session["EmailID"].ToString());
        SqlCommand cmd = new SqlCommand("Select id,Course_Name from tbl_Courses where EID='" + EID + "' and Active='True'", conn);
        conn.Open();
        ddCourseType.Items.Clear();
        ddCourseType.Items.Add("All");
        ddCourseType.AppendDataBoundItems = true;
        ddCourseType.DataSource = cmd.ExecuteReader();
        ddCourseType.DataTextField = "Course_Name";
        ddCourseType.DataValueField = "id";
        ddCourseType.DataBind();
        conn.Close();

    }