因为知道了被选中的行和列的索引,所以可以通过把显示控件的Visible设置为false,编辑控件的Visible设置为true来把某个独立的单元格设置为编辑模式。 然后通过清除单元格的属性来删除被选中单元格的单击事件。
下面有一些代码用于回发服务器后设置焦点到编辑控件,如果编辑控件是DropDownList的话,那么它的SelectedValue要设置为显示控件的值,如果编辑控件是TextBox的话,那么为了做好编辑的准备就要使它的文本被选中。// 获得被选中单元格的显示控件并设置其不可见
Control _displayControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[1];
_displayControl.Visible = false;
// 获得被选中单元格的编辑控件并设置其可见
Control _editControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[3];
_editControl.Visible = true;
// 清除被选中单元格属性以删除click事件
_gridView.Rows[_rowIndex].Cells[_columnIndex].Attributes.Clear();
在这个Demo中,我把事件被触发的历史记录也写到了页里。// 设置焦点到被选中的编辑控件
ClientScript.RegisterStartupScript(GetType(), "SetFocus",
"<script>document.getElementById('" + _editControl.ClientID + "').focus();</script>");
// 如果编辑控件是DropDownList的话
// SelectedValue设置为显示控件的值
if (_editControl is DropDownList && _displayControl is Label)
...{
((DropDownList)_editControl).SelectedValue = ((Label)_displayControl).Text;
}
// 如果编辑控件是TextBox的话则选中文本框内文本
if (_editControl is TextBox)
...{
((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
}
如果GridView处于编辑模式的话,那么要在RowUpdating事件里去查找被选中行的每一个单元格。 如果发现单元格处于编辑模式的话,那么就调用“更新”代码。 在这个Demo中,数据保存在DataTable里,而这个DataTable则储存在session中。
// 循环每一列以找到处于编辑模式下的单元格
for (int i = 1; i < _gridView.Columns.Count; i++)
...{
// 获得单元格的编辑控件
Control _editControl = _gridView.Rows[e.RowIndex].Cells[i].Controls[3];
if (_editControl.Visible)
...{
. update the data
}
}
