第一次写,还不知道怎么下手,望大家给批评批评!
在服务器端用一个文本框来显示当前所有的选择项,以","进行分割,ViewState["ZYKC"]用来保存所有的选择CheckBox的值
protected void cbl_SubjectList_SelectedIndexChanged(object sender, EventArgs e)
{
string sOld = ViewState["ZYKC"].ToString();
string sNew = "";
foreach (ListItem eachItem in cbl_SubjectList.Items)
{
if (eachItem.Selected)
{
if (sNew.Length > 0)
{
sNew = sNew + "," + eachItem.Text;
}
else
{
sNew = eachItem.Text;
}
}
}
ViewState["ZYKC"] = sNew;
if (sOld.Length < sNew.Length)//当前所做操作为选择
{
if (tb_KCMC.Text.Length > 0)
{
tb_KCMC.Text += "," + this.getDifferentStr(sNew, sOld);
}
else
{
tb_KCMC.Text = this.getDifferentStr(sNew, sOld);
}
}
else //当前所做操作为取消
{
string str = this.getDifferentStr(sOld, sNew);
tb_KCMC.Text = this.getSelectByOrder(tb_KCMC.Text, str);
}
}
//获得当前操作所选择的CheckBox的值
private string getDifferentStr(string sOld, string sNew)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(",");
string[] arr_old = reg.Split(sOld);
string[] arr_new = reg.Split(sNew);
for (int i = 0; i < arr_old.Length; i++)
{
int flag =0;//存在标志
for (int j = 0; j < arr_new.Length; j++)
{
if (arr_new[j].Equals(arr_old[i]))
{
flag = 1;
break;
}
}
if (flag.Equals(0))
{
return arr_old[i];
}
}
return "";
}
//如果当前所做的操作是取消一个CheckBox的选择,把值取消,保持顺序不变
private string getSelectByOrder(string sOld, string currentSelect)
{
if (!sOld.Equals(currentSelect))
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(",");
string[] arr_old = reg.Split(sOld);
int index = 0;
string str_SelectByOrder = "";
for (int i = 0; i < arr_old.Length; i++)
{
if (!arr_old[i].Equals(currentSelect))
{
if (str_SelectByOrder.Length > 0)
{
str_SelectByOrder += "," + arr_old[i];
}
else
{
str_SelectByOrder = arr_old[i];
}
}
}
return str_SelectByOrder;
}
else
{
return "";
}
}