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

求助:关于datagrid的简单问题
请问我在DataGrid对象Grid1中加入了一个checkbox模板列chk   希望在页面提交时将被选选种的行对象保存进一个对象数组object[]   rowob中请问chk的OnCheckedChanged事件该如何写呀?谢谢各位了!

------解决方案--------------------
ArrayList arrObject = new ArrayList();
for (int i = 0; i < DataGrid.Rows.Count; i++)
{
CheckBox cbs = DataGrid.Rows[i].Cells[0].FindControl( "sSelect ") as CheckBox;
if (cbs.Checked)
{
int sid = int.Parse(DataGrid.Rows[i].Cells[1].Text.ToString().Trim());
arrObject.Add(sid);
}
}
------解决方案--------------------
just try this following demo:

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

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

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

<script runat= "server ">
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
// 首次加载数据一定要放在 !IsPostBack 内,
// 避免回发的时候再次绑定数据,覆盖复选框状态
LoadProductData();
}
}

void chk_CheckedChanged(object sender, EventArgs e)
{
// 触发此事件的 CheckBox
CheckBox chk = sender as CheckBox;
// 得到 CheckBox 所在行
DataGridItem item = chk.NamingContainer as DataGridItem;
// 得到 DataGrid,当然这里可以直接引用控件ID
DataGrid grd = item.NamingContainer as DataGrid;
// 得到主键
int productId = (int)grd.DataKeys[item.ItemIndex];
Label lblProductName = item.FindControl( "lblProductName ") as Label;
Response.Write(item.ItemIndex);
Response.Write(lblProductName.Text);
// more codes
// ...
//System.Diagnostics.Debug.Assert(false, productId.ToString());
}

void LoadProductData()
{
DataTable dt = CreateProductTable();
DataGrid1.DataSource = dt;
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( "CategoryID ", typeof(int));
tbl.Columns.Add( "HasPic ", typeof(bool));
tbl.Columns.Add( "Reviewed ", typeof(bool));
DataRow row = tbl.NewRow();
row[0] = 1;
row[1] = "Chai ";
row[2] = 1;
row[3] = true;
row[4] = false;
tbl.Rows.Add(row);

row = tbl.NewRow();
row[0] = 2;
row[1] = "Chang ";
row[2] = 1;
row[3] = false;
row[4] = false;
tbl.Rows.Add(row);

row = tbl.NewRow();
row[0] = 3;
row[1] = "Aniseed Syrup ";
row[2] = 2;
row[3] = true;
row[4] = false;
tbl.Rows.Add(row);

row = tbl.NewRow();
row[0] = 4;
row[1] = "Chef Anton 's Cajun Seasoning ";
row[2] = 2;
row[3] = false;
row[4] = true;
tbl.Rows.Add(row);

row