您好,登錄后才能下訂單哦!
原文作者:楊友山
原文地址:http://blog.csdn.net/yysyangyangyangshan/article/details/22438077
前面看了如何增加和刪除Gridview數據,但是無論怎樣Gridview的數據除了展示給用戶外,還需要進行編輯后保存的。
也就是將Gridview的數據獲取下來傳到后臺,然后后臺經過識別和處理獲得數據,保存至數據庫中。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> </head> <body id="Body1" runat="server"> <form id="Form1" runat="server"> <asp:Button ID="btnAdd" runat="server" OnClientClick="return SaveBatch();return false;" Text="批量保存"/> <asp:GridView ID="dgPersons" runat="server" EnableViewState="false" CellPadding="4" GridLines="Horizontal" PageChange="TextBox" AutoGenerateColumns="False" SortMode="Total" ForeColor="#333333" CellSpacing="1" Width="60%" ShowNoRecordTip="True"> <Columns> <asp:TemplateField> <ItemTemplate> <%#Container.DataItemIndex +1%> <input id="hideID" type="hidden" runat="server" value='<%#Eval("p_id")%>' /> </ItemTemplate> <HeaderTemplate> <span>序號</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <span> <%#Eval("p_name")%></span> </ItemTemplate> <HeaderTemplate> <span>姓名</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <span> <%#Eval("p_age")%></span> </ItemTemplate> <HeaderTemplate> <span>年齡</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <span> <%#Eval("p_sex")%></span> </ItemTemplate> <HeaderTemplate> <span>性別</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="txtRemark" runat="server" Text='<%#Eval("p_remark")%>' Width="120px" Height="30px"/> </ItemTemplate> <HeaderTemplate> <span>備注</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <a href ="JavaScript:viod(0)" </ItemTemplate> <HeaderTemplate> <span>操作</span> </HeaderTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" HorizontalAlign="Center" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <RowStyle HorizontalAlign="Center" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView> </form> </body> <script type="text/javascript" src="/Scripts/Ajax.js"></script> <script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script> <script language="javascript" type="text/javascript"> var dgPersonsID = "<%= dgPersons.ClientID %>"; $(document).ready(function () { $("#dgPersons tr").eq(1).hide(); }); function GetGridViewDatas() { var dgs = document.getElementById(dgPersonsID); if (dgs.rows == null || dgs.rows.length < 2) { alert("沒有數據!"); return; } var gridobj = new Object(); gridobj.ID = dgs.rows[1].cells[0].children[0].value; gridobj.Name = dgs.rows[1].cells[1].children[0].innerHTML; gridobj.Age = dgs.rows[1].cells[2].children[0].innerHTML; gridobj.Sex = dgs.rows[1].cells[3].children[0].innerHTML; gridobj.Remark = dgs.rows[1].cells[4].children[0].value; for (var i = 2; i < dgs.rows.length; i++) { gridobj.ID += "," + dgs.rows[i].cells[0].children[0].value; gridobj.Name += "," + dgs.rows[i].cells[1].children[0].innerHTML; gridobj.Age += "," + dgs.rows[i].cells[2].children[0].innerHTML; gridobj.Sex += "," + dgs.rows[i].cells[3].children[0].innerHTML; gridobj.Remark += "," + dgs.rows[i].cells[4].children[0].value; } return gridobj; } //批量保存 function SaveBatch() { var gridDatas = GetGridViewDatas(); var saveDatas = gridDatas; saveDatas.operateType = "SaveAll"; var htmlObjects = $.ajax({ type: "POST", data: saveDatas, async: true, success: function (result) { if (result != "false") { alert("保存成功!"); } else { alert("保存失敗!"); } }, error: function (result) { alert("保存失敗!"); } }); return false; } //單個保存 function SaveSingle(obj) { var elm = event.target || event.srcElement; if (elm.disabled) { return false; } var row = obj.parentElement.parentElement; var gridobj = new Object(); gridobj.snID = row.cells[0].children[0].value; gridobj.Name = row.cells[1].children[0].innerHTML; gridobj.Age = row.cells[2].children[0].innerHTML; gridobj.Sex = row.cells[3].children[0].innerHTML; gridobj.Remark = row.cells[4].children[0].value; var saveData = gridobj; saveData.operateType = "SaveSingleData"; var htmlobj = $.ajax({ type: "POST", data: saveData, async: true, success: function (result) { if (result != "false") { alert("保存成功!"); } else { alert("保存失敗!"); } }, error: function (result) { alert("保存失敗!"); } }); return false; } </script> </html>
public partial class ChildFrm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { switch (Request["operateType"]) { case "SaveAll": SaveAllData(); return; case "SaveSingleData": SaveSingleData(); return; default: break; } if (!IsPostBack) { DataTable dt = InitData(); this.dgPersons.DataSource = dt; this.dgPersons.DataBind(); } } private DataTable InitData() { DataTable PersonCollect = new DataTable(); PersonCollect = new DataTable(); PersonCollect.Columns.Add("p_id"); PersonCollect.Columns.Add("p_name"); PersonCollect.Columns.Add("p_age"); PersonCollect.Columns.Add("p_sex"); PersonCollect.Columns.Add("p_remark"); if (PersonCollect.Rows.Count < 1) { for (int i = 0; i < 11; i++) { DataRow nrow = PersonCollect.NewRow(); nrow["p_id"] = System.Guid.NewGuid().ToString(); nrow["p_name"] = "西北白楊樹"; nrow["p_age"] = 27; nrow["p_sex"] = "男"; nrow["p_remark"] = string.Empty; PersonCollect.Rows.Add(nrow); } } return PersonCollect; } protected void SaveSingleData() { string id = Request["snID"].ToString().Trim() ; string name = Request["Name"].ToString().Trim(); string age = Request["Age"].ToString().Trim(); string sex = Request["Sex"].ToString().Trim(); string remark = Request["Remark"].ToString().Trim(); bool savesuccess = true; //獲取到了list拿到數據庫去保存吧,然后將是否保存成功賦值給savesuccess,前臺根據這個變量來提示 //這里是要生成一個json字符串給前臺提示用 //可以多加幾個屬性,讓提示內容更豐富 ArrayList list = new ArrayList(); Hashtable ht = new Hashtable(); ht.Add("Success", savesuccess.ToString().ToLower()); list.Add(ht); JavaScriptSerializer json = new JavaScriptSerializer(); string jsonResult = json.Serialize(list); SendTextMessage(jsonResult); } protected void SaveAllData() { string id = Request["ID"].ToString(); string name = Request["Name"].ToString(); string age = Request["Age"].ToString(); string sex = Request["Sex"].ToString(); string remark = Request["Remark"].ToString(); string[] ids = SplitString(id); string[] names = SplitString(name); string[] ages = SplitString(age); string[] sexs = SplitString(sex); string[] remarks = SplitString(remark); List<Person> resultList = new List<Person>(); if (ids != null && ids.Length > 0) { for (int i = 0; i < ids.Length; i++) { Person m = new Person(); m.ID = ids[i]; m.Name = names[i]; m.Age = ages[i]; m.Sex = sexs[i]; m.Remark = remarks[i]; resultList.Add(m); } } bool savesuccess = true; //獲取到了list拿到數據庫去保存吧,然后將是否保存成功賦值給savesuccess,前臺根據這個變量來提示 //這里是要生成一個json字符串給前臺提示用 //可以多加幾個屬性,讓提示內容更豐富 ArrayList list = new ArrayList(); Hashtable ht = new Hashtable(); ht.Add("Success", savesuccess.ToString().ToLower()); list.Add(ht); JavaScriptSerializer json = new JavaScriptSerializer(); string jsonResult = json.Serialize(list); SendTextMessage(jsonResult); } private string[] SplitString(string value) { if (string.IsNullOrEmpty(value)) { return new string[0]; } return value.Split(','); } private List<Results> GetResults(bool result,string message) { List<Results> response = new List<Results>(); Results r = new Results(); r.Success = result.ToString().ToLower(); r.Message = message; response.Add(r); return response; } protected void SendTextMessage(string message) { Response.ContentType = "text/plain"; Response.Write(message); Response.End(); } }
public class Person { private string id; public string ID { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string age; public string Age { get { return age; } set { age = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } private string remark; public string Remark { get { return remark; } set { remark = value; } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。