首页 > 代码库 > 【转】GridView 加载空行并点击编辑每一个单元格
【转】GridView 加载空行并点击编辑每一个单元格
1 代码 2 3 <script runat="server"> 4 protectedvoid Button1_Click(object sender, System.EventArgs e) 5 { 6 GridView1.DataSource = GetData(); 7 GridView1.DataBind(); 8 } 9 10 protectedvoid Button2_Click(object sender, System.EventArgs e) 11 { 12 string s = String.Empty; 13 for (int i =0; i <5; i++) 14 { 15 for (int j =0; j <5; j++) 16 { 17 s = s +"<li>第 "+ i.ToString() +" 行第 "+ j.ToString() +" 列的值是:"+ Request.Form["txt"+ i.ToString() +"_"+ j.ToString()]; 18 } 19 } 20 ret.Text = s; 21 // 以下代码只是为了实现在表格里面保留原来的值,如果不需要则可以删除。 22 GridView1.DataSource = GetData(); 23 GridView1.DataBind(); 24 } 25 26 protectedvoid GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) 27 { 28 if (e.Row.RowType == DataControlRowType.DataRow) 29 { 30 System.Data.DataRowView dv = (System.Data.DataRowView)e.Row.DataItem; 31 for (int i =0; i < e.Row.Cells.Count; i++) 32 { 33 e.Row.Cells[i].Attributes.Add("onclick", "showEdit("+ e.Row.RowIndex.ToString() +","+ i.ToString() +")"); 34 e.Row.Cells[i].Text ="<input onblur=‘lostfocus(this)‘ name=‘txt"+ e.Row.RowIndex.ToString() +"_"+ i.ToString() +"‘ readonly=‘readonly‘ class=‘noborder‘ value=http://www.mamicode.com/‘"+ dv[i].ToString() +"‘/>"; 35 } 36 } 37 } 38 39 private System.Data.DataTable GetData() 40 { 41 System.Data.DataTable dt =new System.Data.DataTable(); 42 for (int i =0; i <5; i++) 43 { 44 dt.Columns.Add(new System.Data.DataColumn("", typeof(System.String))); 45 } 46 47 for (int i =0; i <5; i++) 48 { 49 dt.Rows.Add(dt.NewRow()); 50 for (int j =0; j <5; j++) 51 { 52 dt.Rows[i][j] = Request.Form["txt"+ i.ToString() +"_"+ j.ToString()]; 53 } 54 } 55 return dt; 56 } 57 58 </script> 59 60 <html xmlns="http://www.w3.org/1999/xhtml"> 61 <head id="Head1" runat="server"> 62 <title></title> 63 <style type="text/css"> 64 .noborder{border-width: 0px;margin:2px;} 65 .hasborder{border-width: 2px;} 66 </style> 67 68 <script type="text/javascript"> 69 function showEdit(r, c) { 70 document.forms[0].elements["txt"+ r +"_"+ c].readOnly =false; 71 document.forms[0].elements["txt"+ r +"_"+ c].className =‘hasborder‘; 72 document.forms[0].elements["txt"+ r +"_"+ c].select(); 73 } 74 function lostfocus(o) { 75 o.className =‘noborder‘ 76 o.readOnly =true; 77 } 78 </script> 79 80 </head> 81 <body> 82 <form id="form1" runat="server"> 83 <asp:GridView ID="GridView1" runat="server" ShowHeader="false" OnRowDataBound="GridView1_RowDataBound"> 84 </asp:GridView> 85 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="加载表格"/> 86 <asp:Button ID="Button2" runat="server" Text="保存数据" OnClick="Button2_Click"/> 87 <asp:Label ID="ret" runat="server"></asp:Label> 88 </form> 89 </body> 90 </html>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。