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

datagrid 中checkbox控制的问题
承接前一问题http://community.csdn.net/Expert/topic/5652/5652860.xml?temp=.2189752
datagrid中最后一列是checkbox
                 buttonA(datagrid之外)
--------------------------------------------
A1:Taiwan
------------------------------------
product_CD0,item_CD,product_name,....□
--------------------------------------------
A2:Hongkong
------------------------------------
product_CD1,item_CD,product_name,....□
product_CD2,item_CD,product_name,....□
product_CD3,item_CD,product_name,....□

--------------------------------------------
A3:China
------------------------------------
product_CD5,item_CD,product_name,....□
--------------------------------------------

1,每个区域中只能有一个checkbox可以使用
2,datagrid中有checkbox被选中的时候,buttonA可用
一个都没有的时候,buttonA不可用


------解决方案--------------------
just try

<%@ Page Language= "C# " %>
<%@ Import Namespace= "System.Data " %>

<%--
http://community.csdn.net/Expert/TopicView3.asp?id=5652860
--%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<script runat= "server ">

private int lastCategoryId = -1; // 私有字段,当前绑定 DataGrid 行的上一行的 CategoryId

void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
LoadProductData();
}
}

protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
DataRowView drv = e.Item.DataItem as DataRowView;
if (drv != null) {
int currentCategoryId = (int)drv[ "CategoryID "];
// 比较当前行 与 上一行 的 CategoryId
if (lastCategoryId != currentCategoryId) {
//
DataGridItem itemCategory = new DataGridItem(-1, -1, ListItemType.Item);
TableCell emptyCell = new TableCell();
emptyCell.Text = GetCategoryName(currentCategoryId);
emptyCell.ColumnSpan = DataGrid1.Columns.Count; // 合并列
itemCategory.Cells.Add(emptyCell);
// 在当前行之前插入一行
DataGrid1.Controls[0].Controls.AddAt(DataGrid1.Controls[0].Controls.Count - 1, itemCategory);
//
lastCategoryId = currentCategoryId;
}
}
}

string GetCategoryName(int categoryId)
{
switch (categoryId) {
case 1 :
return "A1:Taiwan ";
case 2:
return "A2:Hongkong ";
case 3:
return "A3:RPC ";
default:
return "unknown ";
}
}

void LoadProductData()
{
DataTable dt = CreateProductTable();
DataView dv = dt.DefaultView;
dv.Sort = "CategoryID, ProductID ";
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}

#region sample data

static DataTable CreateProductTable()
{
DataTable tbl = new DataTable( "Products ");

tbl.Columns.Add( "ProductID ", typeof(int));
tbl.Columns.Add( "ProductName ", typeof(string));
tbl.Columns.Add( "Cat