public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = BuildGridViewDataSource();
GridView1.DataBind();
}
SetGridViewEditRow();
}
private void SetGridViewEditRow()
{
if (H_EditRowIndex.Value != "")
{
int editIndex = Convert.ToInt32(H_EditRowIndex.Value);
GridView1.EditIndex = editIndex;
GridView1.DataSource = BuildGridViewDataSource();
GridView1.DataBind();
}
}
/// <summary>
/// 用来做例子中的数据源
/// </summary>
/// <returns></returns>
private DataTable BuildGridViewDataSource()
{
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["Number"] = "1000";
dr["Name"] = "张三";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Number"] = "1001";
dr["Name"] = "李四";
dt.Rows.Add(dr);
return dt;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//实现单击时确发编辑
//e.Row.Attributes.Add("onclick", "OnClickedRow('" + e.Row.RowIndex + "');");
//实现双击时确发编辑
e.Row.Attributes.Add("ondblclick", "OnClickedRow('" + e.Row.RowIndex + "');");
}
}
}
HTML code<body>
<form id="form1" runat="server">
<div>
<asp:GridView Width="500" ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Number" HeaderText="编号" />
<asp:BoundField DataField="Name" HeaderText="姓名" />
</Columns>
</asp:GridView>
<input id="H_EditRowIndex" type="hidden" runat="server" />
</div>
</form>
</body>
</html>
JScript code <script type="text/javascript">
function OnClickedRow(rowIndex)
{
document.getElementById("H_EditRowIndex").value = rowIndex;
form1.submit();
}
</script>