Editable Grid View System using BootStrap in ASP.Net
In this blog, I’m explaining how to make a gridview editable using bootstrap in asp.net.
Step 1:
First, create an asp.net empty web application and add a web form to the solution.
Step 2:
Now add a gridview by drag and drop from the toolbox and give these properties and event:
|
As you make true to these properties, your gridview will look like this:
Step 3:
Now add the below code in the .aspx.cs file:
protectedvoid Page_Load(object sender, EventArgs e)
{
DataLoad();
}
publicvoid DataLoad()
{
string message = string.Empty;
try
{
SqlConnection connection = GlobalClass.OpenConnection(out message);
if (connection != null && string.IsNullOrEmpty(message))
{
string cmd = "select * from GridView";
SqlDataAdapter dAdapter = newSqlDataAdapter(cmd, connection);
DataSet ds = newDataSet();
dAdapter.Fill(ds);
dt = ds.Tables[0];
//Bind the fetched data to gridview
grdvCrudOperation.DataSource = dt;
grdvCrudOperation.DataBind();
grdvCrudOperation.Columns[3].Visible = false;
}
}
catch (Exception ex)
{ message = ex.Message;
}
finally
{
GlobalClass.CloseConnection(out message);
}
}
When you run the above code, this will display all values from the Employee table.
Step 4:
To make the gridview editable, create three-button field inside gridview
<asp:ButtonFieldCommandName="detail" ControlStyle-CssClass="btn btn-info" ButtonType="Button"Text="Detail"HeaderText="Detailed View">
<ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
<asp:ButtonFieldCommandName="editRecord" ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Edit"HeaderText="Edit Record">
<ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
<asp:ButtonFieldCommandName="deleteRecord" ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Delete"HeaderText="Delete Record">
<ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
Step 5:
Now add the code to the events:
Details
protectedvoid GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("detail"))
{
int ID = Convert.ToInt32(grdvCrudOperation.DataKeys[index].Value.ToString());
IEnumerable<DataRow> query = from i in dt.AsEnumerable() where i.Field<int>("ID").Equals(ID)
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);
}
}
RowEditing
protectedvoid GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = grdvCrudOperation.Rows[index];
HfUpdateID.Value = HttpUtility.HtmlDecode(gvrow.Cells[3].Text).ToString(); txtNameUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text); txtEmailIDUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
txtAddressUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text);
txtContactUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[7].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);
}
}
protectedvoid btnSave_Click(object sender, EventArgs e)
{
string message = string.Empty;
try {
SqlConnection connection = GlobalClass.OpenConnection(out message);
if (connection != null && string.IsNullOrEmpty(message))
{
SqlCommand cmd = newSqlCommand("Proc_UpdateGridView", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID",HfUpdateID.Value);
cmd.Parameters.AddWithValue("@Name", txtNameAdd.Text.Trim());
cmd.Parameters.AddWithValue("@EmailID", txtEmailIDAdd.Text.Trim());
cmd.Parameters.AddWithValue("@Address", txtAddressAdd.Text.Trim());
cmd.Parameters.AddWithValue("@Contact", txtContactAdd.Text.Trim());
int row = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
message = ex.Message;
}
finally
{
GlobalClass.CloseConnection(out message);
} DataLoad();
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);
}
RowDeleting
protectedvoid GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("deleteRecord"))
{
string code = grdvCrudOperation.DataKeys[index].Value.ToString();
HfDeleteID.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);
}
}
protectedvoid btnDelete_Click(object sender, EventArgs e)
{
string message = string.Empty;
try
{
SqlConnection connection = GlobalClass.OpenConnection(out message);
if (connection != null && string.IsNullOrEmpty(message))
{
SqlCommand cmd = newSqlCommand("Proc_DeleteGridView", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", HfDeleteID.Value);
int row = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
message = ex.Message;
}
finally
{
GlobalClass.CloseConnection(out message); }
DataLoad();
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);
}
RecordInserted
protectedvoid btnAdd_Click(object sender, EventArgs e) //Open Model popup
{
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);
}
protectedvoid btnAddRecord_Click(object sender, EventArgs e)
{ string message = string.Empty;
try
{
SqlConnection connection = GlobalClass.OpenConnection(out message);
if (connection != null && string.IsNullOrEmpty(message))
{ SqlCommand cmd = newSqlCommand("Proc_SaveGridView", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", txtNameAdd.Text.Trim());
cmd.Parameters.AddWithValue("@EmailID", txtEmailIDAdd.Text.Trim());
cmd.Parameters.AddWithValue("@Address", txtAddressAdd.Text.Trim());
cmd.Parameters.AddWithValue("@Contact", txtContactAdd.Text.Trim());
int row = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
message = ex.Message;
}
finally
{
GlobalClass.CloseConnection(out message);
}
DataLoad();
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);
}
GridView.aspx
<%@PageLanguage="C#" AutoEventWireup="true"CodeBehind="GridView.aspx.cs"Inherits="GridViewCRUDBootstrapExample.Default"%>
<!DOCTYPEhtml> <htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
<linkhref="Styles/bootstrap.css" rel="stylesheet"/>
<scriptsrc="Scripts/jquery-1.8.2.js"></script> <scriptsrc="Scripts/bootstrap.js"></script>
</head>
<body>
<formid="form1"runat="server">
<divstyle="width: 90%; margin-right: 5%; margin-left: 5%; text-align: center">
<asp:ScriptManagerrunat="server"ID="ScriptManager1"/> <h1>Grid View System</h1>
<asp:UpdatePanelID="upCrudGrid"runat="server">
<ContentTemplate> <asp:GridViewID="grdvCrudOperation"runat="server"Width="940px"HorizontalAlign="Center"
OnRowCommand="GridView1_RowCommand"AutoGenerateColumns="false"AllowPaging="true"
DataKeyNames="ID"CssClass="table table-hover table-striped">
<Columns>
<asp:ButtonField CommandName="detail"ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Detail"HeaderText="Detailed View">
<ControlStyleCssClass="btn btn-info"></ControlStyle> </asp:ButtonField>
<asp:ButtonField CommandName="editRecord"ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Edit"HeaderText="Edit Record"> <ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
<asp:ButtonField CommandName="deleteRecord"ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Delete"HeaderText="Delete Record"> <ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
<asp:BoundField DataField="ID"HeaderText="ID"/>
<asp:BoundField DataField="Name"HeaderText="Name"/>
<asp:BoundField DataField="EmailID"HeaderText="EmailID"/>
<asp:BoundField DataField="Address"HeaderText="Address"/>
<asp:BoundField DataField="Contact"HeaderText="Contact NO"/>
</Columns> </asp:GridView>
<asp:ButtonID="btnAdd"runat="server"Text="Add New Record"CssClass="btn btn-info"OnClick="btnAdd_Click"/> </ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
<divid="detailModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
<divclass="modal-header">
<buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
<h3id="myModalLabel">Details</h3>
</div>
<divclass="modal-body">
<asp:UpdatePanelID="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="Name"HeaderText="Name"/>
<asp:BoundField DataField="EmailID"HeaderText="EmailID"/>
<asp:BoundField DataField="Address"HeaderText="Address"/>
<asp:BoundField DataField="Contact"HeaderText="Contact NO"/>
</Fields>
</asp:DetailsView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="grdvCrudOperation"EventName="RowCommand"/>
<asp:AsyncPostBackTrigger ControlID="btnAdd"EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
<divclass="modal-footer">
<buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Close</button>
</div> </div>
</div>
<divid="editModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="editModalLabel"aria-hidden="true">
<divclass="modal-header">
<buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
<h3id="editModalLabel">Edit Record</h3>
</div> <asp:UpdatePanelID="upEdit"runat="server">
<ContentTemplate> <divclass="modal-body">
<asp:HiddenField ID="HfUpdateID"runat="server"/>
<tableclass="table">
<tr>
<td>Name : </td>
<td>
<asp:TextBox ID="txtNameUpdate"runat="server"></asp:TextBox></td>
<td>
</tr>
<tr> <td>EmailID</td>
<td>
<asp:TextBox ID="txtEmailIDUpdate"runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Address</td>
<td>
<asp:TextBox ID="txtAddressUpdate"runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Contact No</td>
<td>
<asp:TextBox ID="txtContactUpdate"runat="server"></asp:TextBox></td>
</tr>
</table>
</div>
<divclass="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"/>
<buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="grdvCrudOperation"EventName="RowCommand"/>
<asp:AsyncPostBackTrigger ControlID="btnSave"EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
</div>
<divid="addModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="addModalLabel"aria-hidden="true">
<divclass="modal-header">
<buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
<h3id="addModalLabel">Add New Record</h3>
</div>
<asp:UpdatePanelID="upAdd"runat="server">
<ContentTemplate>
<divclass="modal-body">
<tableclass="table table-bordered table-hover">
<tr> <td>Name : </td>
<td>
<asp:TextBox ID="txtNameAdd"runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>EmailID :</td>
<td> <asp:TextBox ID="txtEmailIDAdd"runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Address:</td>
<td>
<asp:TextBox ID="txtAddressAdd"runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Contact No:</td>
<td>
<asp:TextBox ID="txtContactAdd"runat="server"></asp:TextBox></td>
</tr>
</table>
</div>
<divclass="modal-footer">
<asp:Button ID="btnAddRecord"runat="server"Text="Add"CssClass="btn btn-info"OnClick="btnAddRecord_Click"/>
<buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddRecord"EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
</div>
<divid="deleteModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="delModalLabel"aria-hidden="true">
<divclass="modal-header">
<buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
<h3id="delModalLabel">Delete Record</h3>
</div> <asp:UpdatePanelID="upDel"runat="server">
<ContentTemplate>
<divclass="modal-body">
Are you sure you want to delete the record?
<asp:HiddenField ID="HfDeleteID"runat="server"/>
</div>
<divclass="modal-footer">
<asp:Button ID="btnDelete"runat="server"Text="Delete"CssClass="btn btn-info"OnClick="btnDelete_Click"/>
<buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Cancel</button>
</div>
</ContentTemplate>
<Triggers> <asp:AsyncPostBackTrigger ControlID="btnDelete"EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</form>
</body>
</html>
Use this BootStrap File :-
|
Download and add the above three files into your projects because it’s mandatory for using the bootstrap libraries and methods.
When you run the project, it will show you all the values from the database.
Output
When you click the “Add New Record” button:
Fill the form with your appropriate values and click on “Add” button. Clicking on “Add” button will insert the record.
When you click the “Detail” button:
When you click the “Edit” button:
Fill the form with your appropriate values and click on “Update” button. Clicking on “Update” button will Updated the record.
When you click the delete button:
I have deleted the “Dev Karan Patel” record.
If you click “Delete” button then record deleted
Nyein Chan
23-Jul-2018I need
Use this BootStrap File :-
<linkhref="Styles/bootstrap.css"rel="stylesheet"/>
<scriptsrc="Scripts/jquery-1.8.2.js"></script>
<scriptsrc="Scripts/bootstrap.js"></script>
link me .
I am beginner level.
Hilman Niroha
29-Mar-2018Hilman Niroha
29-Mar-2018Teodoro Carvajal
21-Feb-2017the source code file Please !
Vicente Basso
11-Feb-2017the source code file Please !
Gavin Wood
26-Jan-2017weimen ho
11-Oct-2016Fadi Awaragi
30-Sep-2016Yll Kallaba
31-Aug-2016the source code file Please !
??????? ?????????
31-Aug-2016Daoose Nox
19-Jul-2016Dennis Sojo
05-Jul-2016Manoj Bhatt
21-Apr-2016Luis Solis
15-Apr-2016Johnny Oz
11-Feb-2016Mehmet polat
02-Feb-2016amaia a
27-Aug-2015Daniel Ramirez
05-Aug-2015Megha Sharma
30-Jul-2015Jorge Perez
12-Jul-2015Hi Kamlakar,
Can you please send me the final project after the modifications you have made so far?
I am having issues displaying the modal forms.
Thanks
Jorge
Nestor Floresca
15-Mar-2015Is it possible to add a dropdown list control on boostrap modal..?
I tried your code and replaced the textbox control with a dropdown list.. The only problem I have, when a user selected a value.. It always return the first item on the dropdown list.. I also noticed when i add an autopostback=true the boostrap modal disappear.. Any suggestion on how to resolve the issue..?
Rainer Schwindel
08-Mar-2015greatings from germany and many thanks for your example. I saved a lot of time in doing it by myself. I only have to problems:
1. I don't het the black background (VS2013, bootstrap 3)
2. after saving the data the modal window closes but in the grid th fields change to edit format
any ideas?
Thank you!
Jose Israel Ble Gonzalez
26-Feb-2015waqas qazi
26-Jan-2015Hi Kamlakar,
Ric Pullen
24-Dec-2014Manoj Pokhare
18-Dec-2014Hi Kamlakar,
I tried your code. Grid is displayed but model is not working. please send me your email id so that I will send my code for your review.Thanks
Manoj P
alp ayder
10-Sep-2014Carlos Freire
02-Sep-2014yasir Babar
27-Aug-2014yasir Babar
27-Aug-2014Anonymous User
27-Aug-2014yasir Babar
26-Aug-2014Anonymous User
26-Aug-2014yasir Babar
25-Aug-2014yasir Babar
23-Aug-2014Nelson Rodriguez
09-Aug-2014Mike Johnson
19-Jun-2014mugisha viktor
14-May-2014when i run this codes ,return this error :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Anonymous User
11-Mar-2014Jolaade Fadare
10-Mar-2014Earl Kimble
20-Feb-2014