一个GridView中判断checkbox是否被选中的问题,高手帮忙看下!

时间:2021-02-27 09:00:28

<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkMail" runat="server" Checked="false"/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle Width="5%" />
</asp:TemplateField>


 try
        {
            foreach (GridViewRow row in MailView.Rows)
            {   ///获取控件
                bool isChecked = ((CheckBox)row.FindControl("checkMail")).Checked;
                CheckBox checkMail = (CheckBox)row.FindControl("checkMail");//.FindControl("CheckMail");
                //string s = MailView.Rows[0].Cells[0].ID.ToString();
                //int s = MailView.Controls.;
                if (checkMail != null)
                {
                    if (checkMail.Checked == true)
                    {
                        ///执行数据库操作
                        string a = "";
                        //mail.DeleteMail(Int32.Parse(MailView.DataKeys[row.RowIndex].Value.ToString()));
                    }
                }
            }


为什么isChecked 始终是FALSE,无论我怎么点checkbox, isChecked始终是FALSE。求解。 

6 个解决方案

#1


autopostback设置为ture

#2


引用 1 楼 caozhy 的回复:
autopostback设置为ture


设置这个属性的话,你每点一次都刷新一次,结果就是一个都点不上

#3


if(!IsPostBack)
 BindData();

#4


页面加载的时候检查IsPostBack,Page_Load先执行,数据被重新绑定了,事件函数后执行,所以状态变成初始状态了。

#5


楼上正解
因为在每次点选择执行事件之前都要先执行page_load事件,控件又会被置为false,绑定数据放在!IsPostBack可以避免.

#6



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataClass;
using System.Data;

namespace m2c.index.Message
{
    public partial class Mes_Send : BasePage
    {
        /// <summary>
        /// 1:添加 2:修改.
        /// </summary>
        private int nTypeID = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!int.TryParse(this.Request.QueryString["nTypeID"], out nTypeID))
            {
                return;
            }

            if (!IsPostBack)
            {
                BindData();
                if (nTypeID == 2)
                {
                    hfMesid.Value = Request.QueryString["nmesid"].ToString();
                    hfUserid.Value = Request.QueryString["nuserid"].ToString();
                    BindCheckBoxList();
                }

            }
        }

        private void BindData()
        {
            DataSet ds = SQLHelper2.ExecuteDataSet(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "select distinct m2c_OSP_DepartMent.* from m2c_OSP_DepartMent left join dbo.m2c_OSP_User on m2c_OSP_DepartMent.autoid=dbo.m2c_OSP_User.DepartMentId where m2c_OSP_DepartMent.IsEnable=1 and dbo.m2c_OSP_User.DepartMentId in(select distinct DepartMentId from dbo.m2c_OSP_User where m2c_OSP_User.IsEnable=1)");
            dlt.DataSource = ds.Tables[0];
            dlt.DataBind();
            ds.Dispose();
        }

        private void BindCheckBoxList()
        {
            for (int i = 0; i < dlt.Items.Count; i++)
            {
                CheckBoxList cbl = (CheckBoxList)dlt.Items[i].FindControl("cbl");
                foreach (ListItem li in cbl.Items)
                {
                    if (li.Value == hfUserid.Value)
                    {
                        li.Selected = true;
                    }
                }

            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bool flag = true;
            string struserid = string.Empty;
            for (int i = 0; i < dlt.Items.Count; i++)
            {
                CheckBoxList cbl = (CheckBoxList)dlt.Items[i].FindControl("cbl");
                foreach (ListItem li in cbl.Items)
                {
                    if (li.Selected)
                    {
                        struserid += "'" + li.Value + "',";
                        flag = false;
                    }
                }

            }

            while (struserid.EndsWith(","))
            {
                struserid = struserid.Substring(0, struserid.Length - 1);
            }
            if (flag)
            {
                Jscript.Alert("请选择发送人");
            }
            else
            {
                if (nTypeID == 1)
                {
                    int strmesid = Convert.ToInt32(SQLHelper2.ExecuteScalar(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "insert into dbo.m2c_OSP_Message (MesContent,Author,IPaddr,[Status],Ntype)values('" + tarContent.Value + "','" + GetUser().User_Id + "','" + StaticMethod.GetClientIP() + "','1','1')select SCOPE_IDENTITY() as mesid;", null));
                    string strsql = "insert into dbo.m2c_OSP_MesUItems (mesid,recuser) select '" + strmesid + "' as mesid,m2c_OSP_User.[User_Id] as recuser from dbo.m2c_OSP_User where m2c_OSP_User.[User_Id] in(" + struserid + ")";
                    SQLHelper2.ExecuteNonQuery(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, strsql, null);
                    Jscript.AlertAndRedirect("发布成功!", "Mes_Send.aspx?nTypeid=1");
                }
                else if (nTypeID == 2)
                {
                    int strmesid = Convert.ToInt32(SQLHelper2.ExecuteScalar(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "insert into dbo.m2c_OSP_Message (MesContent,Author,IPaddr,[Status],Ntype)values('" + tarContent.Value + "','" + GetUser().User_Id + "','" + StaticMethod.GetClientIP() + "','1','2')select SCOPE_IDENTITY() as mesid;", null));
                    string strsql2 = "insert into dbo.m2c_OSP_MesUItems (mesid,recuser) select '" + strmesid + "' as mesid,m2c_OSP_User.[User_Id] as recuser from dbo.m2c_OSP_User where m2c_OSP_User.[User_Id] in(" + struserid + ")";
                    SQLHelper2.ExecuteNonQuery(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, strsql2, null);
                    Jscript.AlertAndRedirect("回复成功!", "Mes_SendList.aspx");
                }
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Jscript.GoHistory(-2);
        }

        protected void cb_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.dlt.Items.Count; i++)
            {
                CheckBox cb = (CheckBox)dlt.Items[i].FindControl("cb");
                CheckBoxList cbl = (CheckBoxList)dlt.Items[i].FindControl("cbl");

                for (int j = 0; j < cbl.Items.Count; j++)
                {
                    if (cb.Checked == true)
                    {
                        cbl.Items[j].Selected = true;
                    }
                    else if (cb.Checked == false)
                    {
                        cbl.Items[j].Selected = false;
                    }

                }

            }
        }

        protected void dlt_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            string strid = dlt.DataKeys[e.Item.ItemIndex].ToString();
            DataSet ds2 = SQLHelper2.ExecuteDataSet(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "select [User_id],[User_id]+'-'+[User_name] as uname from dbo.m2c_OSP_User left join dbo.m2c_OSP_DepartMent on m2c_OSP_User.DepartMentId=m2c_OSP_DepartMent.autoid where m2c_OSP_User.isenable=1 and dbo.m2c_OSP_DepartMent.isenable=1 and m2c_OSP_DepartMent.autoid='" + strid + "'");
            CheckBoxList cbl = (CheckBoxList)e.Item.FindControl("cbl");
            cbl.DataSource = ds2.Tables[0];
            cbl.DataTextField = "uname";
            cbl.DataValueField = "User_id";
            cbl.DataBind();
            ds2.Dispose();
        }

    }
}



楼主你照着我的代码改总会吧? 

#1


autopostback设置为ture

#2


引用 1 楼 caozhy 的回复:
autopostback设置为ture


设置这个属性的话,你每点一次都刷新一次,结果就是一个都点不上

#3


if(!IsPostBack)
 BindData();

#4


页面加载的时候检查IsPostBack,Page_Load先执行,数据被重新绑定了,事件函数后执行,所以状态变成初始状态了。

#5


楼上正解
因为在每次点选择执行事件之前都要先执行page_load事件,控件又会被置为false,绑定数据放在!IsPostBack可以避免.

#6



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataClass;
using System.Data;

namespace m2c.index.Message
{
    public partial class Mes_Send : BasePage
    {
        /// <summary>
        /// 1:添加 2:修改.
        /// </summary>
        private int nTypeID = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!int.TryParse(this.Request.QueryString["nTypeID"], out nTypeID))
            {
                return;
            }

            if (!IsPostBack)
            {
                BindData();
                if (nTypeID == 2)
                {
                    hfMesid.Value = Request.QueryString["nmesid"].ToString();
                    hfUserid.Value = Request.QueryString["nuserid"].ToString();
                    BindCheckBoxList();
                }

            }
        }

        private void BindData()
        {
            DataSet ds = SQLHelper2.ExecuteDataSet(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "select distinct m2c_OSP_DepartMent.* from m2c_OSP_DepartMent left join dbo.m2c_OSP_User on m2c_OSP_DepartMent.autoid=dbo.m2c_OSP_User.DepartMentId where m2c_OSP_DepartMent.IsEnable=1 and dbo.m2c_OSP_User.DepartMentId in(select distinct DepartMentId from dbo.m2c_OSP_User where m2c_OSP_User.IsEnable=1)");
            dlt.DataSource = ds.Tables[0];
            dlt.DataBind();
            ds.Dispose();
        }

        private void BindCheckBoxList()
        {
            for (int i = 0; i < dlt.Items.Count; i++)
            {
                CheckBoxList cbl = (CheckBoxList)dlt.Items[i].FindControl("cbl");
                foreach (ListItem li in cbl.Items)
                {
                    if (li.Value == hfUserid.Value)
                    {
                        li.Selected = true;
                    }
                }

            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bool flag = true;
            string struserid = string.Empty;
            for (int i = 0; i < dlt.Items.Count; i++)
            {
                CheckBoxList cbl = (CheckBoxList)dlt.Items[i].FindControl("cbl");
                foreach (ListItem li in cbl.Items)
                {
                    if (li.Selected)
                    {
                        struserid += "'" + li.Value + "',";
                        flag = false;
                    }
                }

            }

            while (struserid.EndsWith(","))
            {
                struserid = struserid.Substring(0, struserid.Length - 1);
            }
            if (flag)
            {
                Jscript.Alert("请选择发送人");
            }
            else
            {
                if (nTypeID == 1)
                {
                    int strmesid = Convert.ToInt32(SQLHelper2.ExecuteScalar(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "insert into dbo.m2c_OSP_Message (MesContent,Author,IPaddr,[Status],Ntype)values('" + tarContent.Value + "','" + GetUser().User_Id + "','" + StaticMethod.GetClientIP() + "','1','1')select SCOPE_IDENTITY() as mesid;", null));
                    string strsql = "insert into dbo.m2c_OSP_MesUItems (mesid,recuser) select '" + strmesid + "' as mesid,m2c_OSP_User.[User_Id] as recuser from dbo.m2c_OSP_User where m2c_OSP_User.[User_Id] in(" + struserid + ")";
                    SQLHelper2.ExecuteNonQuery(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, strsql, null);
                    Jscript.AlertAndRedirect("发布成功!", "Mes_Send.aspx?nTypeid=1");
                }
                else if (nTypeID == 2)
                {
                    int strmesid = Convert.ToInt32(SQLHelper2.ExecuteScalar(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "insert into dbo.m2c_OSP_Message (MesContent,Author,IPaddr,[Status],Ntype)values('" + tarContent.Value + "','" + GetUser().User_Id + "','" + StaticMethod.GetClientIP() + "','1','2')select SCOPE_IDENTITY() as mesid;", null));
                    string strsql2 = "insert into dbo.m2c_OSP_MesUItems (mesid,recuser) select '" + strmesid + "' as mesid,m2c_OSP_User.[User_Id] as recuser from dbo.m2c_OSP_User where m2c_OSP_User.[User_Id] in(" + struserid + ")";
                    SQLHelper2.ExecuteNonQuery(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, strsql2, null);
                    Jscript.AlertAndRedirect("回复成功!", "Mes_SendList.aspx");
                }
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Jscript.GoHistory(-2);
        }

        protected void cb_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.dlt.Items.Count; i++)
            {
                CheckBox cb = (CheckBox)dlt.Items[i].FindControl("cb");
                CheckBoxList cbl = (CheckBoxList)dlt.Items[i].FindControl("cbl");

                for (int j = 0; j < cbl.Items.Count; j++)
                {
                    if (cb.Checked == true)
                    {
                        cbl.Items[j].Selected = true;
                    }
                    else if (cb.Checked == false)
                    {
                        cbl.Items[j].Selected = false;
                    }

                }

            }
        }

        protected void dlt_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            string strid = dlt.DataKeys[e.Item.ItemIndex].ToString();
            DataSet ds2 = SQLHelper2.ExecuteDataSet(SQLHelper2.ConnectionStringLocalTransaction, CommandType.Text, "select [User_id],[User_id]+'-'+[User_name] as uname from dbo.m2c_OSP_User left join dbo.m2c_OSP_DepartMent on m2c_OSP_User.DepartMentId=m2c_OSP_DepartMent.autoid where m2c_OSP_User.isenable=1 and dbo.m2c_OSP_DepartMent.isenable=1 and m2c_OSP_DepartMent.autoid='" + strid + "'");
            CheckBoxList cbl = (CheckBoxList)e.Item.FindControl("cbl");
            cbl.DataSource = ds2.Tables[0];
            cbl.DataTextField = "uname";
            cbl.DataValueField = "User_id";
            cbl.DataBind();
            ds2.Dispose();
        }

    }
}



楼主你照着我的代码改总会吧?