日期:2014-05-20  浏览次数:20717 次

关于GridView删除多行记录的问题
我是个.net的初学者
怎么弄都弄不好GridView删除多行记录(C#)
希望高手告诉我代码
谢谢


------解决方案--------------------
先申明,以下代碼是針對ASP.NET的。

GridView的第一列要設計成復選框。

<asp:TemplateField>
<HeaderTemplate>
<input id= "cbSelectAll " type= "checkbox " onclick= "javascript:SelectAllCheckboxes(this); " />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID= "cbSelectItem " runat= "server " /> </ItemTemplate>
<asp:HiddenField ID= "hfID " Value= ' <%# Eval( "ID ") %> ' runat= "server " />
<HeaderStyle Width= "20px " />
</asp:TemplateField>

cbSelectAll是全選和全不選之用途;
<%# Eval( "ID ") %> 是關鍵字段;
onclick= "javascript:SelectAllCheckboxes(this); "所調用的客戶端腳本如下:

<script language= "javascript " type= "text/javascript ">
function SelectAllCheckboxes(spanChk){
var oItem = spanChk.children;
var theBox=(spanChk.type== "checkbox ")?spanChk:spanChk.children.item[0];
xState=theBox.checked;
table = theBox.parentNode.parentNode.parentNode;
elm1=table.childNodes;
for(j=0;j <elm1.length;j++)
{
elm2 = elm1[j].childNodes;
for(m=0;m <elm2.length;m++)
{
elm = elm2[m].childNodes;
for(i=0;i <elm.length;i++)
{
if(elm[i].type== "checkbox " && elm[i].id!=theBox.id)
{
if(elm[i].checked!=xState)
elm[i].click();
break;
}
}
}
}
}
</script>

后台程序取得所有選中行的關鍵字實現代碼如下:

public ArrayList GetSelectedKeyValues()
{
ArrayList selectedRows = new ArrayList();
foreach (GridViewRow row in gvDefenceArea.Rows)
{
bool isChecked = ((CheckBox)row.FindControl( "cbSelectItem ")).Checked;
if (isChecked)
selectedRows.Add(row.Cells[1].Text);
}
return selectedRows;
}