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

关于DataGrid的TemplateColumn的问题,请高人指点! - .NET技术 / C#
DataGrid的TemplateColumn里有一个CheckBox,我的问题是CheckBox似乎不能激发OnItemCommand事件,那么我怎么可以在CheckBox的Checked属性发生改变的时,知道发生变化的这个CheckBox时DataGrid中的哪一行的呢?

也就是说,我要从CheckBox出发,找出它位于DataGrid中的那一行?

希望高手帮帮忙,在线等!!谢谢!!

------解决方案--------------------
两个方法:

/// <summary>
/// 此方法适合绑定列,不适合数据表主键绑定了Label的情况.
/// </summary>
/// <param name= "grid "> </param>
/// <param name= "controlID "> checkBox控件ID </param>
/// <param name= "primaryKeyIndex "> 要获取数据表中列的索引 </param>
/// <returns> </returns>
public static ArrayList GetSelected(GridView grid, string controlID, int primaryKeyIndex)
{
ArrayList aryChecked = new ArrayList();
for (int i = 0; i < grid.Rows.Count; i++)
{
CheckBox chk = (CheckBox)grid.Rows[i].FindControl(controlID);
if (chk.Checked)
aryChecked.Add(grid.Rows[i].Cells[primaryKeyIndex].Text.ToString());
}
return aryChecked;
}

/// <summary>
///
/// </summary>
/// <param name= "grid "> </param>
/// <param name= "checkBoxControlID "> </param>
/// <param name= "primaryKeyControlID "> </param>
/// <returns> </returns>
public static ArrayList GetSelected(GridView grid, string checkBoxControlID, string primaryKeyControlID)
{
Label lbl_id = null;
//
ArrayList aryChecked = new ArrayList();
for (int i = 0; i < grid.Rows.Count; i++)
{
CheckBox chk = (CheckBox)grid.Rows[i].FindControl(checkBoxControlID);
if (chk.Checked)
{
if (grid.Rows[i].FindControl(primaryKeyControlID) is Label)
{
lbl_id = (Label)grid.Rows[i].FindControl(primaryKeyControlID);
aryChecked.Add(lbl_id.Text.Trim());
}
}
}
return aryChecked;
}
------解决方案--------------------
ItemCommand事件里,循环所有的行,判断CheckBox是否选取,取着行的索引就可以了.
------解决方案--------------------
在 protected void myGrid_ItemCommand(object source, DataGridCommandEventArgs e)
事件中写,应该就可以了,我也可以采用为CheckBox手工添加事件的方法
------解决方案--------------------
这个都是要遍历DataGrid的所有项的

protected void btnDelete_Click(object sender, EventArgs e)
{
CheckBox chk;
foreach (DataGridItem dgi in DataGrid1.Items)
{
chk = (CheckBox)dgi.FindControl( "chkSelect ");
if (chk != null)
{
if (chk.Checked)
{

//可以使用DataGrid1.DataKeys[dgi.ItemIndex].ToString()得到当前主键值

}
}
}
}