ASP.NET: GridView CRUD using Twitter Bootstrap Modal Popup
来源:互联网 发布:网络卖警服 编辑:程序博客网 时间:2024/05/18 06:08
相关源代码下载连接请点击这里
In one of my articles I explained how to use Twitter Bootstrap Modal Popup Plugin to show gridview row details in a modal popup on selecting a particular gridview row. This article was well received and as a result I got many requests to write an article explaining the usage of Twitter bootstrap's Modal Plugin to implement create, read, update and delete operations in ASP.NET GridView.
2. Before proceeding to create a web page, let us set up a sample dummy mysql table for our use in this application. Use the below create statement to create a table in your mysql server.
mysql> create table tblCountry(Code varchar(10),Name varchar(100),Continent varchar(50),Region varchar(50),Population bigint,IndepYear int);
For your ease I am giving few insert statements with dummy values with which you can add a few rows in the table you have created instantly.
insert into tblCountry values('ABW','Aruba','North America','Caribbean',10300000,1956);
insert into tblCountry values('AFG','Afghanistan','Asia','Southern and Central Asia',227200,1919);
insert into tblCountry values('AGO','Angola','Africa','Central Africa',128780008,1975);
insert into tblCountry values('AIA','Anguilla','North America','Caribbean',80000,1942);
insert into tblCountry values('ALB','Albania','Europe','Southern Europe',3401200,1912);
First of all add a ScriptManager control to your webform as we are going to do everything in AJAX way. Then let us add an Update Panel with Gridview and add asynchronouspostback trigger for GridViewRowCommand Event. We are not going to use the default crud functionality that GridView provides but going to achieve the same using GridView RowCommand Event just like how we displayed details in my previous article.
<asp:ScriptManager runat="server" ID="ScriptManager1" /> <!-- Placing GridView in UpdatePanel--> <asp:UpdatePanel ID="upCrudGrid" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" Width="940px" HorizontalAlign="Center" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" AllowPaging="true" DataKeyNames="Code" CssClass="table table-hover table-striped"> <Columns> <asp:ButtonField CommandName="detail" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="Detail" HeaderText="Detailed View"> <ControlStyle CssClass="btn btn-info"></ControlStyle> </asp:ButtonField> <asp:ButtonField CommandName="editRecord" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="Edit" HeaderText="Edit Record"> <ControlStyle CssClass="btn btn-info"></ControlStyle> </asp:ButtonField> <asp:ButtonField CommandName="deleteRecord" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="Delete" HeaderText="Delete Record"> <ControlStyle CssClass="btn btn-info"></ControlStyle> </asp:ButtonField> <asp:BoundField DataField="Code" HeaderText="Code" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Continent" HeaderText="Continent" /> <asp:BoundField DataField="Region" HeaderText="Region" /> <asp:BoundField DataField="Population" HeaderText="Population" /> <asp:BoundField DataField="IndepYear" HeaderText="Independence Year" /> </Columns> </asp:GridView> <asp:Button ID="btnAdd" runat="server" Text="Add New Record" CssClass="btn btn-info" OnClick="btnAdd_Click" /> </ContentTemplate> <Triggers> </Triggers> </asp:UpdatePanel>
In the above code, there are three button fields for performing operations such as detail, edit and delete. Later in this article I will explain how to use the Command Names of these buttons in GridView's RowCommand Event to open modal pop ups.
Next let us add code for detail view popup that displays selected gridview row in a detailsview control.
<!-- Detail Modal Starts here--><div id="detailModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Detailed View</h3> </div> <div class="modal-body"> <asp:UpdatePanel ID="UpdatePanel2" runat="server"> <ContentTemplate> <asp:DetailsView ID="DetailsView1" runat="server" CssClass="table table-bordered table-hover" BackColor="White" ForeColor="Black" FieldHeaderStyle-Wrap="false" FieldHeaderStyle-Font-Bold="true" FieldHeaderStyle-BackColor="LavenderBlush" FieldHeaderStyle-ForeColor="Black" BorderStyle="Groove" AutoGenerateRows="False"> <Fields> <asp:BoundField DataField="Code" HeaderText="Code" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Continent" HeaderText="Continent" /> <asp:BoundField DataField="Population" HeaderText="Population" /> <asp:BoundField DataField="IndepYear" HeaderText="Independence Year" /> </Fields> </asp:DetailsView> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="RowCommand" /> <asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" /> </Triggers> </asp:UpdatePanel> <div class="modal-footer"> <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div></div><!-- Detail Modal Ends here -->
Next let us add code for Edit Modal Popup that contains required controls to update the existing values in a particular record.
<!-- Edit Modal Starts here --><div id="editModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="editModalLabel">Edit Record</h3> </div> <asp:UpdatePanel ID="upEdit" runat="server"> <ContentTemplate> <div class="modal-body"> <table class="table"> <tr> <td>Country Code : <asp:Label ID="lblCountryCode" runat="server"></asp:Label> </td> </tr> <tr> <td>Population : <asp:TextBox ID="txtPopulation" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Country Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Continent: <asp:TextBox ID="txtContinent1" runat="server"></asp:TextBox> </td> </tr> </table> </div> <div class="modal-footer"> <asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label> <asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" /> <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="RowCommand" /> <asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" /> </Triggers></asp:UpdatePanel></div><!-- Edit Modal Ends here -->
Code for Add Modal Popup goes after this, that contains controls that enables an user to create a new record in the database.
<!-- Add Record Modal Starts here--><div id="addModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="addModalLabel">Add New Record</h3> </div> <asp:UpdatePanel ID="upAdd" runat="server"> <ContentTemplate> <div class="modal-body"> <table class="table table-bordered table-hover"> <tr> <td>Country Code : <asp:TextBox ID="txtCode" runat="server"> </asp:TextBox> </td> </tr> <tr> <td>Country Name : <asp:TextBox ID="txtCountryName" runat="server"> </asp:TextBox> </td> </tr> <tr> <td>Continent Name: <asp:TextBox ID="txtContinent" runat="server"> </asp:TextBox> </td> </tr> <tr> <td>Region: <asp:TextBox ID="txtRegion" runat="server"> </asp:TextBox> </td> </tr> <tr> <td>Population: <asp:TextBox ID="txtTotalPopulation" runat="server"> </asp:TextBox> </td> </tr> <tr> <td>Year of Independence <asp:TextBox ID="txtIndYear" runat="server"> </asp:TextBox> </td> </tr> </table> </div> <div class="modal-footer"> <asp:Button ID="btnAddRecord" runat="server" Text="Add" CssClass="btn btn-info" OnClick="btnAddRecord_Click" /> <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="btnAddRecord" EventName="Click" /> </Triggers> </asp:UpdatePanel></div><!--Add Record Modal Ends here-->
Finally let us add code for confirming delete operation in a modal popup as shown below.
<!-- Delete Record Modal Starts here--><div id="deleteModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="delModalLabel">Delete Record</h3> </div> <asp:UpdatePanel ID="upDel" runat="server"> <ContentTemplate> <div class="modal-body"> Are you sure you want to delete the record? <asp:HiddenField ID="hfCode" runat="server" /> </div> <div class="modal-footer"> <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="btn btn-info" OnClick="btnDelete_Click" /> <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Cancel</button> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" /> </Triggers> </asp:UpdatePanel></div><!--Delete Record Modal Ends here -->
Now we are done with the markup. Note that I have used UpdatePanel on every section of code, just to make the GridView operations function totally in AJAX way without refreshing the whole page.
3. Add MySql Database connection string to Web.config file.
<add connectionString="server=localhost;uid=root;password=xxxx;database=world; pooling=false;" providerName="MySql.Data.MySqlDataClient" name="MySqlConnString" />
4. In the code-behind page, let us first write code to fetch data from database and display on Page Load. This code to fetch data from database and bind to gridview for display will be reused in the later sections since after every operation (create, update or delete) we have to reload our gridview with latest information from database.
DataTable dt;protected void Page_Load(object sender, EventArgs e){ BindGrid(); }public void BindGrid(){ try { //Fetch data from mysql database string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString; MySqlConnection conn = new MySqlConnection(connString); conn.Open(); string cmd = "select * from tblCountry limit 10"; MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd, conn); DataSet ds = new DataSet(); dAdapter.Fill(ds); dt = ds.Tables[0]; //Bind the fetched data to gridview GridView1.DataSource = dt; GridView1.DataBind(); } catch (MySqlException ex) { System.Console.Error.Write(ex.Message); } }
Next let us write code to perform core operations (add, update and delete record from database).
private void executeUpdate(string code,int population,string countryname,string continent){ string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString; try { MySqlConnection conn = new MySqlConnection(connString); conn.Open(); string updatecmd = "update tblCountry set Population=@population, Name=@countryname,Continent=@continent where Code=@code"; MySqlCommand updateCmd = new MySqlCommand(updatecmd,conn); updateCmd.Parameters.AddWithValue("@population", population); updateCmd.Parameters.AddWithValue("@countryname", countryname); updateCmd.Parameters.AddWithValue("@continent", continent); updateCmd.Parameters.AddWithValue("@code", code); updateCmd.ExecuteNonQuery(); conn.Close(); } catch (MySqlException me) { System.Console.Error.Write(me.InnerException.Data); }}private void executeAdd(string code, string name, string continent,string region, int population, int indyear){ string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString; try { MySqlConnection conn = new MySqlConnection(connString); conn.Open(); string insertcmd = "insert into tblCountry (Code,Name,Continent,Region,Population,IndepYear) values (@code,@name,@continent,@region,@population,@indyear)"; MySqlCommand addCmd = new MySqlCommand(insertcmd, conn); addCmd.Parameters.AddWithValue("@code", code); addCmd.Parameters.AddWithValue("@name", name); addCmd.Parameters.AddWithValue("@continent", continent); addCmd.Parameters.AddWithValue("@region", region); addCmd.Parameters.AddWithValue("@population", population); addCmd.Parameters.AddWithValue("@indyear", indyear); addCmd.ExecuteNonQuery(); conn.Close(); } catch (MySqlException me) { System.Console.Write(me.Message); }}private void executeDelete(string code){ string connString = ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString; try { MySqlConnection conn = new MySqlConnection(connString); conn.Open(); string deletecmd = "delete from tblCountry where Code=@code"; MySqlCommand delCmd = new MySqlCommand(deletecmd, conn); delCmd.Parameters.AddWithValue("@code", code); delCmd.ExecuteNonQuery(); conn.Close(); } catch (MySqlException me) { System.Console.Write(me.Message); }}
When the page initially runs, records are picked up from database and displayed in gridview. Once the user clicks the detail/edit/delete button for any row, control is passed to Gridview's RowCommand Event with the corresponding Command Name of the button that is clicked.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){ int index = Convert.ToInt32(e.CommandArgument); if (e.CommandName.Equals("detail")) { string code = GridView1.DataKeys[index].Value.ToString(); IEnumerable<DataRow> query = from i in dt.AsEnumerable() where i.Field<String>("Code").Equals(code) select i; DataTable detailTable = query.CopyToDataTable<DataRow>(); DetailsView1.DataSource = detailTable; DetailsView1.DataBind(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(@"<script type='text/javascript'>"); sb.Append("$('#detailModal').modal('show');"); sb.Append(@"</script>"); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false); } else if (e.CommandName.Equals("editRecord")) { GridViewRow gvrow = GridView1.Rows[index]; lblCountryCode.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text).ToString(); txtPopulation.Text = HttpUtility.HtmlDecode(gvrow.Cells[7].Text); txtName.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text); txtContinent1.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text); lblResult.Visible = false; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(@"<script type='text/javascript'>"); sb.Append("$('#editModal').modal('show');"); sb.Append(@"</script>"); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditModalScript", sb.ToString(), false); } else if (e.CommandName.Equals("deleteRecord")) { string code = GridView1.DataKeys[index].Value.ToString(); hfCode.Value = code; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(@"<script type='text/javascript'>"); sb.Append("$('#deleteModal').modal('show');"); sb.Append(@"</script>"); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DeleteModalScript", sb.ToString(), false); }}
Heads Up!
Finally, in the 'OnClick' event of the buttons present inside each of the modal popup let us add necessary code to call the core methods that executes update, add and delete operations. This part also updates the user once the operation is completed successfully and closes the modal popup after refreshing the gridview with latest data
.
// Handles Update Button Click Eventprotected void btnSave_Click(object sender, EventArgs e){string code=lblCountryCode.Text;int population=Convert.ToInt32(txtPopulation.Text);string countryname = txtName.Text;string continent=txtContinent1.Text;executeUpdate(code,population,countryname,continent); BindGrid(); System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append(@"<script type='text/javascript'>");sb.Append("alert('Records Updated Successfully');");sb.Append("$('#editModal').modal('hide');");sb.Append(@"</script>");ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false); }//Handles Add record button click in main formprotected void btnAdd_Click(object sender, EventArgs e){System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append(@"<script type='text/javascript'>");sb.Append("$('#addModal').modal('show');");sb.Append(@"</script>");ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AddShowModalScript", sb.ToString(), false); }//Handles Add button click in add modal popupprotected void btnAddRecord_Click(object sender, EventArgs e){string code = txtCode.Text;string name = txtCountryName.Text;string region = txtRegion.Text;string continent = txtContinent.Text;int population = Convert.ToInt32(txtTotalPopulation.Text);int indyear = Convert.ToInt32(txtIndYear.Text);executeAdd(code, name, continent, region,population, indyear);BindGrid();System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append(@"<script type='text/javascript'>");sb.Append("alert('Record Added Successfully');");sb.Append("$('#addModal').modal('hide');");sb.Append(@"</script>");ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AddHideModalScript", sb.ToString(), false);}//Handles Delete button click in delete modal popupprotected void btnDelete_Click(object sender, EventArgs e){string code=hfCode.Value;executeDelete(code);BindGrid();System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append(@"<script type='text/javascript'>");sb.Append("alert('Record deleted Successfully');");sb.Append("$('#deleteModal').modal('hide');");sb.Append(@"</script>");ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "delHideModalScript", sb.ToString(), false);}
That's it! When the user clicks on detail button for any row,
When the user clicks on 'Edit' Button,
Once the update is done,
When the user clicks Add new Record button in the main form,
原文地址:
http://www.programming-free.com/2013/09/gridview-crud-bootstrap-modal-popup.html
- ASP.NET: GridView CRUD using Twitter Bootstrap Modal Popup
- ASP.NET: Display GridView Row Details in Modal Popup using Twitter Bootstrap
- 在Asp.net MVC 使用bootstrap 的modal dialog 实现Popup
- Bootstrap Pagination for ASP.NET GridView
- ASP.NET GridView的Bootstrap分页样式
- ASP.NET GridView的Bootstrap分页样式
- 在ASP.NET MVC 4中使用TWITTER BOOTSTRAP
- Bootstrap+Knockout.JS+ASP.Net MVC3+PetaPOCO实现CRUD操作
- asp.net做crud
- Developing a Multi-Select ASP.NET GridView using JQuery
- ASP.NET : Freeze GridView Header using GridViewScroll jQuery plugin
- Bootstrap modal
- Bootstrap-Modal
- BootStrap Modal
- bootstrap modal
- modal (Bootstrap)
- asp.net 存储过程CRUD
- ASP.NET Popup Control的学习
- 被7/11/13整除的数特征
- 文件上传下载删除工具类
- JSP四种属性范围
- HttpsURLConnection 安全传输(HTTPS--Secure Hypertext Transfer Protocol-安全超文本传输协议)
- html页面表格导出excel出现科学计数法问题的解决
- ASP.NET: GridView CRUD using Twitter Bootstrap Modal Popup
- Ubuntu下安装ActiveMQ
- java_静态类
- 别人遇到的问题
- 导航栏添加多个按键
- 黑马程序员_软件计数器
- AngularJS资源大集锦
- 【MFC基础教程】API与SDK的区别与联系
- java位操作符总结