日期:2014-05-18  浏览次数:20389 次

asp.net checkBox 问题
我想就是 AB 会随着我选择按钮 而变化,即使取消按钮 ,只要还有一个按钮已选,AB也不会是空值
如我已选择了CheckBox1,CheckBox2,CheckBox4
AB值是ABD
然后取消CheckBox1
AB值是BD

以下是我的想法 但不知问题出在哪

public partial class Default2 : System.Web.UI.Page
{
  public string a, b, c, d;
  public string AB(string a, string b, string c, string d)
  {
  return a + b + c + d;
  }
  public void CheckBox1_CheckedChanged(object sender, EventArgs e)
  {
  if (CheckBox1.Checked == true)
  a = "A";
  else
  a = "";
   
  }
  public void CheckBox2_CheckedChanged(object sender, EventArgs e)
  {
  if (CheckBox2.Checked == true)
  b= "B";
  else
  b="";
   
  }
  public void CheckBox3_CheckedChanged(object sender, EventArgs e)
  {
  if (CheckBox3.Checked == true)
  c= "C";
  else
  c = "";
   
  }

  public void CheckBox4_CheckedChanged(object sender, EventArgs e)
  {
  if (CheckBox4.Checked == true)
  d = "D";
  else
  d = "";

  }


------解决方案--------------------
你这样明显不行啊,因为CheckBox每回发一次,页面类就会重新实例化的,这样你定义的a,b,c,d都会重新定义的,而回发后只会执行对应CheckBox的事件,只会对a,b,c,d中的某一个赋值,最终调用的AB(string a, string b, string c, string d)方法当然只会出现某一个字符了。想解决这个问题,可以每个CheckBox都订阅同一个事件,而在这个事件中判断哪些CheckBox被勾选,再给对应的a,b,c,d赋值,再调用AB方法就可以了
C# code

public partial class Default2 : System.Web.UI.Page
    {
        public string a, b, c, d;
        public string AB(string a, string b, string c, string d)
        {
            return a + b + c + d;
        }
        //共用的回调事件
        public void CheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox1.Checked == true)
                a = "A";
            else
                a = "";
            if (CheckBox2.Checked == true)
                b = "B";
            else
                b = "";
            if (CheckBox3.Checked == true)
                c = "C";
            else
                c = "";
            if (CheckBox4.Checked == true)
                d = "D";
            else
                d = "";

            AB(a, b, c, d);
        }
    }

------解决方案--------------------
我写个具体的,你懂的


HTML code


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm27.aspx.cs" Inherits="jquerytest.WebForm27" %>

<!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>
    <script src="jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="checkbox" name="newsletter" checked="checked" value="A" /> 篮球
        <input type="checkbox" name="newsletter" value="B" />  足球
        <input type="checkbox" name="newsletter" checked="checked" value="C" /> 羽毛球
        <input ty