GridView暫時不知道是否有多選功能,老師又讓做出來只能按自己的方法實現
數據的綁定不再寫直接寫過程和思路,在GridView中添加模板在模板里加入CheckBox,但在後臺不能訪問建好的CheckBox,問題就出在這裏。
遍歷CheckBox的屬性和事件,發現了CheckBox有個CheckedChanged於是後臺藉助這個事件來得到具體是哪個CheckBox激發的時間。
想辦法確立選中的Checkbox與選中的數據對應,CheckBox的屬性可以喝數據庫的信息綁定,於是我將每條數據的id與checkbox的CssClass屬性綁定在一起
於是可以通過2得到選中數據的id,並且賦值給Session存儲用戶的選擇。
當用戶最後點擊確定刪除後,再從Session中讀取用戶最後選擇的數據,用戶在選擇過程中會有選中然後又取消的可能,通過程序保證用戶最終選擇的數據的id值都存儲在Seesion【“xyuan”】中
//獲取用戶最終的選擇
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox x = (CheckBox)sender;//1這裏用來接收具體是哪CheckBox激發的事件
string x1 = Convert.ToString(Session["xyuan"]);
string h1 = "a";
if (x1 == "")//x1等於空說明用戶是第一次點擊,所以直接複製,第二次可能是取消選擇。
{
Session["xyuan"] = Session["xyuan"] + x.CssClass + ",";//2得到cssclass的值,值與id相等
}
else
{
string[] n = Session["xyuan"].ToString().Split(',');//3通過特殊符號將保存在session中的字符串變爲單個字符
Session["x"] = "";
foreach (string h in n)//4通過該循環得到最後選中的是哪個,即用戶可能選擇後又放棄選擇,
{
if (h == x.CssClass)//如果session中含有被選中的行則爲h1賦值,
{
h1 = "l";
}
else
{//session中如果與不被選中的行不同則賦值給x若果有則不賦值,h1的值改變ze將x複製個xyuan,若不變則相反
//session["x"]中保存的永遠是被選中
Session["x"] = Session["x"] + h+",";
}
}
if (h1 == "a")//如果h1的值不變書名Session【“xyuan”】中不含有被選中的數據,然後將數據保存進去
{
Session["xyuan"] = Session["xyuan"] + x.CssClass + ",";//得到cssclass的值,值與id相等
}
else if (h1 == "l")//h1如果等於l說明session中含有被選中的行,但Session【“x”】中不會保存重複的項,所以將值賦給Session【“xyuan”】以便下次重新操作
{
Session["xyuan"] = Session["x"].ToString();
}
}
}
//刪除用戶最終的選擇
protected void Button1_Click(object sender, EventArgs e)
{ int sid=1;
string[] n = Session["xyuan"].ToString().Split(',');
foreach (string x in n)
{
if (x == "")
{ }
else {
sid = Convert.ToInt32(x);
xclass1.ExecuteNonQuery(sid);//調用刪除方法循環刪除數據
}
}
Response.Redirect("xyhgl.aspx");
}