I have a problem when I edit data select from grid view and update on bootstrap modal.
ASPX:
<asp:GridView ID="gvcat" CssClass="table table-bordered font-13" Width="500px" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ID") %>' OnClick="lnkView_Click" data-toggle="modal" data-target="#myModal" causesvalidation="false">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
String CS = ConfigurationManager.ConnectionStrings["TFRWebAppConnectionString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(CS))
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("CategoryCreateOrUpdate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#ID", (hfID.Value == "" ? 0 : Convert.ToInt32(hfID.Value)));
sqlCmd.Parameters.AddWithValue("#Name", txtName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Description", txtDescription.Text.Trim());
sqlCmd.ExecuteNonQuery();
gvcat.DataBind();
}
}
catch (Exception)
{
}
protected void lnkView_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["TFRWebAppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
int ID = Convert.ToInt32((sender as LinkButton).CommandArgument);
using (SqlCommand cmd = new SqlCommand("SELECT * from tblCategory WHERE ID = #ID", con))
{
cmd.Parameters.AddWithValue("#ID", ID); // this line was mising in your code
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtcategory = new DataTable();
sda.Fill(dtcategory);
con.Close();
hfID.Value = ID.ToString();
txtName.Text = dtcategory.Rows[0]["Name"].ToString();
txtDescription.Text = dtcategory.Rows[0]["Description"].ToString();
}
}
}
}
aspx body:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×</button>
<h4 class="modal-title">
Add New Metal Group</h4>
</div>
<div class="modal-body">
<asp:HiddenField ID="hfID" runat="server" />
<div class="row">
<div class="form-group-sm">
<div class="col-md-3">
<asp:TextBox ID="txtName" CssClass="form-control" placeholder="Category Name" type="text" runat="server"></asp:TextBox>
<asp:TextBox ID="txtDescription" CssClass="form-control" placeholder="Description" type="text" runat="server"></asp:TextBox>
<%-- <asp:RequiredFieldValidator ID="RequiredFieldValidatorDescription" CssClass="text-danger" runat="server" ErrorMessage="This field is Required !" ControlToValidate="txtDescription"></asp:RequiredFieldValidator>--%>
</div>
</div>
</div>
<div class="row">
<div class="form-group-sm">
<div class="col-md-6">
<asp:Button ID="btnSave" CssClass="btn btn-sm" runat="server" OnClick="btnSave_Click" Text="Save" />
<asp:Button ID="btnClear" CssClass="btn btn-sm" runat="server" OnClick="btnClear_Click" Text="Clear" />
</div>
</div>
</div>
</div>
</div>
</div>
Related
I want to do all database related commands with modals (add, edit, delete)
I do this with Entity Framework
But when I press the Create button in the modal, nothing happens
Please help me to do this operation
Reverently
My ProductControl Page Html Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ProductControl.aspx.cs" Inherits="AppData.Pages.ProductControl" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="Head" runat="server">
<link rel="stylesheet"href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css">
<script src="../Scripts/jquery-3.6.0.slim.min.js"></script>
<script src="../Scripts/Site.js"></script>
</asp:Content>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="container">
<div class="row">
<div class="col-md-12 table-responsive" id="ProductDiv">
<div class="d-flex justify-content-between align-items-center mb-3 mt-3">
<h4>List of Products</h4>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">
Add Product
</button>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:GridView ID="GridView" runat="server" CssClass="table text-center table-bordered table-hover" HeaderStyle-CssClass="table-dark" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Font-Size="Small">
<HeaderTemplate>Row</HeaderTemplate>
<ItemTemplate><%# Container.DataItemIndex+1 %></ItemTemplate>
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="Barcode" HeaderText="Barcode" />
<asp:TemplateField HeaderText="Commands" ItemStyle-Font-Size="Small">
<ItemTemplate>
<asp:LinkButton CssClass="btn btn-warning" ID="BtnDelete" runat="server">Edit</asp:LinkButton>
<asp:LinkButton CssClass="btn btn-danger" ID="BtnEdit" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="row">
<asp:Label ID="LblNotFound" runat="server" Text="No Product Found" CssClass="col-12 alert alert-danger text-center" Visible="false"></asp:Label>
</div>
</div>
<!-- Modal -->
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<div class="modal" id="myModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Record</h4>
<button type="button" class="btn btn-success close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<asp:TextBox ID="Name" placeholder="Name" runat="server"></asp:TextBox>
<asp:TextBox ID="Price" placeholder="Price" runat="server"></asp:TextBox>
<asp:TextBox ID="Type" placeholder="Type" runat="server"></asp:TextBox>
<asp:TextBox ID="Barcode" placeholder="Barcode" runat="server"></asp:TextBox>
</div>
<div class="modal-footer">
<asp:Button ID="BtnCreate" runat="server" CssClass="btn btn-success" data-dismiss="modal" Text="Create" OnClick="BtnCreate_Click" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
My ProductControl Page Backend Code:
using AppData.Models;
using System;
using System.Collections.Generic;
using System.EnterpriseServices;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AppData.Pages
{
public partial class ProductControl : System.Web.UI.Page
{
Models.ProductDbEntities Db = new Models.ProductDbEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (GridView.Rows.Count > 0)
{
LblNotFound.Visible = false;
}
else
{
GridView.DataSource = Db.TblProducts.ToList();
GridView.DataBind();
}
}
protected void BtnCreate_Click(object sender, EventArgs e)
{
TblProduct Row = new TblProduct();
Row.Name = Name.Text;
Row.Price = Price.Text;
Row.Type = Type.Text;
Row.Barcode = Convert.ToInt64(Price.Text);
Db.TblProducts.Add(Row);
Db.SaveChanges();
Response.Redirect("~/Pages/ProductControl.aspx");
}
}
}
Unfortunately, I was unable to remove the Run Code Snippet
The button inside the UpdatePanel will not work.
Your problem probably is similar to this one
Button click not working inside update panel
As per Sid M:
set ChildrenAsTriggers of the UpdatePanel to true and add EventName="Click" to the UpdatePanel tag like this:
<asp:UpdatePanel>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnBlock" EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
I have a form that has various buttons on that when clicked display a modal popup. The popup displays correctly on the screen, but no data appears in any of the fields.
When I step through the code I can see that the data is being assigned to the relevant controls (textbox or label) but nothing appears. In my project I have several other forms that also have popups and these work as they should. I have even used the code from these forms to try and solve the issue but with no success.
This is the code where the user clicks the button to display the popup
<div class="tab-pane fade" id="tabDiary">
<div class="col-md-12">
<asp:UpdatePanel ID="updatePanelDiary" runat="server">
<ContentTemplate>
<%--<asp:Timer ID="timerDiary" runat="server" Interval="15000" OnTick="timerDiary_Tick"></asp:Timer>--%>
<asp:Repeater ID="rptDiary" runat="server" OnItemDataBound="rptDiary_ItemDataBound">
<HeaderTemplate>
<div class="col-md-12 text-right">
<div class="form-group">
<asp:Button ID="btnDiary" runat="server" Text="New Diary Item" OnClick="btnDiary_Click" CssClass="btn btn-warning" Visible="true" />
<div class="clearfix"></div>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr class="tabHeaderRow">
<td>Date</td>
<td>Entered By</td>
<td>Comments</td>
<td>Action Date</td>
<td></td>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem,"DateEntered") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"AddedBy") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Comments") %></td>
<td><asp:Label ID="lblActionDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"ActionDate") %>'></asp:Label></td>
<td><asp:Button ID="btnEditDiaryEntry" runat="server" CssClass="btn btn-primary btn-sm" Text="Edit" CommandName="EditDiaryEntry"
OnCommand="btnEditDiaryEntry_Command" CommandArgument='<%#Eval("DiaryID") %>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="clearfix"></div>
</div>
This is the code behind:
protected void btnEditDiaryEntry_Command(object sender, CommandEventArgs e)
{
Int32 DiaryID = Convert.ToInt32(e.CommandArgument);
SqlCommand cmd = new SqlCommand("sp_GetDiaryEntry", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DiaryID", DiaryID);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtEditComment.Text = dr["Comments"].ToString();
txtEditScheduleDiary.Text = dr["ActionDate"].ToString();
}
dr.Close();
cnn.Close();
ScriptManager.RegisterStartupScript(_parentControl, _parentControl.GetType(), "Modal", " DisplayEditDiaryModal()", true);
Master.GetMenuData();
txtEditScheduleDiary.Text = "hello david";
}
And this is the code to display the popup
<script type="text/javascript">
function DisplayEditDiaryModal() {
$('#<%=pnlDiaryEdit.ClientID%>').modal('show');
}
</script>
This is the code for the modal:
<asp:Panel ID="pnlDiaryEdit" runat="server" class="modal fade" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="well well-md">
<fieldset>
<legend class="text-center header"><asp:Label ID="Label31" Text="Edit Diary Entry" runat="server" Visible="true"></asp:Label></legend>
<asp:HiddenField ID="hidDiaryID" runat="server" />
<div class="form-group">
<div class="col-md-3">
<asp:Label ID="lblEditComment" runat="server" Text="Comment"></asp:Label>
</div>
<div class="col-md-9">
<asp:TextBox ID="txtEditComment" runat="server" CssClass="form-control" TextMode="MultiLine" Rows="10" Wrap="true" ></asp:TextBox>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-md-3">
<asp:Label ID="lblEditSchedule" runat="server" Text="Schedule Event"></asp:Label>
</div>
<div class="col-md-6">
<asp:TextBox ID="txtEditScheduleDiary" runat="server" CssClass="form-control" Visible="true" ></asp:TextBox>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-md-12 text-right">
<asp:Button ID="btnCancelEdit" runat="server" Text="Cancel" CssClass="btn btn-primary" OnClientClick="HideEditDiaryModal(); return false;" />
<asp:Button ID="btnEditDiary" runat="server" Text="Edit" CssClass="btn btn-success" OnClick="btnEditDiary_Click" />
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</div>
As I have already said this code works on other forms within the project. Any help would be much appreciated.
Have you tried adding updatePanelDiary.Update()?
protected void btnEditDiaryEntry_Command(object sender, CommandEventArgs e)
{
Int32 DiaryID = Convert.ToInt32(e.CommandArgument);
SqlCommand cmd = new SqlCommand("sp_GetDiaryEntry", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DiaryID", DiaryID);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtEditComment.Text = dr["Comments"].ToString();
txtEditScheduleDiary.Text = dr["ActionDate"].ToString();
}
dr.Close();
cnn.Close();
ScriptManager.RegisterStartupScript(_parentControl, _parentControl.GetType(), "Modal", " DisplayEditDiaryModal()", true);
Master.GetMenuData();
txtEditScheduleDiary.Text = "hello david";
updatePanelDiary.Update();
}
And add UpdateMode="Conditional" to your update panel
<asp:UpdatePanel ID="updatePanelDiary" runat="server" UpdateMode="Conditional">
I have a grid and what I am trying to do is when edit button is clicked of any row, the data of that row should be passed to textboxes. But I am unable to do so. I have used RowCommand but still unable to fetch the data.
asp code
<div class="form-group">
<label>FULL NAME</label>
<input type="text" class="form-control" runat="server" id="Name" autocomplete="off" />
</div>
<div class="form-group">
<label>GENDER</label><span class="required">*</span>
<select class="form-control" id="selectGender" runat="server" style="height: 34px;">
<option value="0">MALE</option>
<option value="1">FEMALE</option>
</select>
</div>
<div class="col-md-12">
<asp:GridView ID="famGrid" Visible="false"
runat="server" OnRowCommand="famGrid_RowCommand">
<Columns>
<asp:TemplateField HeaderText="S No." ItemStyle-Width="3%">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
HeaderText="FULL NAME" DataField="Name">
<ItemStyle VerticalAlign="Top" />
</asp:BoundField>
<asp:BoundField
HeaderText="GENDER" DataField="selectGender">
<ItemStyle VerticalAlign="Top" />
</asp:BoundField>
<asp:TemplateField HeaderText="EDIT">
<ItemTemplate>
<asp:Button Text="EDIT" ID="btnEdit" CommandName="ChangeStatus" formnovalidate="formnovalidate" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind
protected void famGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int selectedRowIndex = -1;
if (e.CommandName == "ChangeStatus")
{
DataTable dt = ViewState["FamilyTable"] as DataTable;
GridViewRow gvr = famGrid.SelectedRow;
lblRow.Text = gvr.Cells[1].Text;
Name.Value = gvr.Cells[2].Text;
selectGender.Items[selectGender.SelectedIndex].Text = gvr.Cells[3].Text;
}
}
catch (Exception)
{
throw;
}
}
I am getting error null reference error.
I've used SelectedIndexChanged. It is working.
protected void famGrid_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = famGrid.SelectedRow;
lblRow.Text = gvr.Cells[1].Text;
Name.Value = gvr.Cells[2].Text;
selectGender.Items[selectGender.SelectedIndex].Text = gvr.Cells[3].Text;
}
Please let us know i which line you are getting exception.
I try to delete data that display in GridView after confirm it using twitter bootstrap. my gridview with modal-dialog as follow
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title clearfix ">
<div>
<b>Name</b>
<div style="float: left;">
</div>
</div>
</h2>
</div>
<div class="panel-body">
<div>
<asp:GridView ID="gridView" DataKeyNames="Id" runat="server"
CssClass="table table-striped table-bordered table-hove"
AutoGenerateColumns="False" HeaderStyle-Font-Bold="true"
OnRowEditing="gridView_RowEditing"
OnRowCancelingEdit="gridView_RowCancelingEdit"
OnRowUpdating="gridView_RowUpdating"
OnRowDeleting="gridView_RowDeleting"
OnRowCommand="gridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="ID" ControlStyle-Width="0px">
<ItemTemplate>
<asp:Label ID="txtid" runat="server" Text='<%#Eval("Id") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblid" runat="server" Width="40px" Text='<%#Eval("Id") %>' />
</EditItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblLName" runat="server" Text='<%#Eval("Location_name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLName" CssClass="form-control" runat="server" Text='<%#Eval("Location_name") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="LocName" AutoCompleteType="Disabled" runat="server" />
<asp:RequiredFieldValidator ID="ReqBrName" runat="server" ControlToValidate="BrName" Display="Dynamic" CssClass="valid" ErrorMessage="?" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:LinkButton ID="lbEdit" CssClass="btn btn-default btn-sm " runat="server" CommandName="Edit">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Edit</asp:LinkButton>
<asp:LinkButton ID="lbDelete" CssClass="btn btn-default btn-sm " runat="server" CommandArgument='<%#Eval("Id")%>' OnClientClick="return ConfirmDelete()">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</asp:LinkButton>
<%-- Delete Form --%>
<div class="modal fade" id="DeleteModal" tabindex="-1" role="dialog" aria-labelledby="delete" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close glyphicon glyphicon-remove" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title" id="">Delete the data</h4>
</div>
<div class="modal-body">
Are You sure?
<asp:Label ID="lblLName1" runat="server" Text='<%#Eval("id") %>' />
<br />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default glyphicon glyphicon-remove" data-dismiss="modal">Cancel</button>
<asp:LinkButton ID="lbde" CssClass="btn btn-default btn-sm " runat="server" CommandName="Delete">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete
</asp:LinkButton>
</div>
</div>
</div>
</div>
<%-- Delete Form --%>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" CssClass="btn btn-default btn-sm " runat="server" CommandName="Update">
<span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Update
</asp:LinkButton>
<asp:LinkButton ID="lbCancel" CssClass="btn btn-default btn-sm " runat="server" CommandName="Cancel">
<span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Cancel
</asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Font-Bold="True"></HeaderStyle>
</asp:GridView>
</div>
</div>
</div>
and my JavaScript function is
<script>
function ConfirmDelete() {
$('#DeleteModal').modal()
return false;
}
</script>
so when I try to delete the record by using the popup model it's not working, the model will work fine but the data in lblLName1 allows will be the first record ID so when I confirm the first record will be deleted
could anyone helps me in that??
Thanks everyone
after trying several ways I found the solution.
first, change the calling button from
<asp:LinkButton ID="lbDelete" CssClass="btn btn-default btn-sm " runat="server" CommandArgument='<%#Eval("Id")%>' OnClientClick="return ConfirmDelete()"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</asp:LinkButton>
to
<asp:LinkButton ID="lbDelete" CssClass="btn btn-default btn-sm" runat="server" CommandArgument='<%#Eval("Id")%>'
OnCommand="lbDelete_Command" CommandName='<%#Eval("Location_name")%>'>
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> حذف</asp:LinkButton>
and in c# call function under lbDelete_Command
protected void lbDelete_Command(object sender, CommandEventArgs e)
{
foreach (GridViewRow row in gridView.Rows)
{
HiddenField hf_id = row.FindControl("hf_Del_ID") as HiddenField;
Label l_name = row.FindControl("lb_Del_Name") as Label;
l_name.Text = e.CommandName.ToString();
hf_id.Value = e.CommandArgument.ToString();
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { ConfirmDelete(); });", true);
}
and I edit the fields under modal-body division like follow
<div class="modal-body">
<asp:HiddenField ID="hf_Del_ID" runat="server" />
Are You sure?
<h4><asp:Label ID="lb_Del_Name" runat="server"/></h4>
</div>
I use the hidden field hf_Del_ID for delete purpose
and the label lb_Del_Name for display only
and also the deleting SQL in C# as follow
try
{
HiddenField hf_id = (HiddenField)gridView.Rows[e.RowIndex].FindControl("hf_Del_ID");
con.Open();
SqlCommand cmd = new SqlCommand("delete from TABLE_NAME where Id=" + hf_id.Value, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
loadData();
lbl_msgDet.ForeColor = Color.Red;
lbl_msgDet.Text = " delete done";
}
}
catch (SqlException ex)
{
lbl_msgDet.ForeColor = Color.Red;
lbl_msgDet.Text = (String)GetGlobalResourceObject("Err_msg", "MsgDeleteErr") + "<br/>" + ex.Message;
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { CallMsg(); });", true);
I hope the solution helps
Thanks
this works for me... very easy
<asp:DataGrid runat="server" ID="dgMyGrid" ValidationGroup="grdMyGrid" OnDeleteCommand="dgRel_DeleteCommand" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn HeaderText="FirstColumn">
<ItemTemplate>
<asp:Label runat="server" ID="FirstColumnID" Text='<%# getFirstColumnName(Eval("FirstColumn").ToString())%>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<div class="modal" id="myModal<%#Eval("MyIDToBound").ToString()%>">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Confirm</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p id="modal-help-text">Are you sure to remove item?</p>
</div>
<div class="modal-footer">
<asp:Button runat="server" ID="btnDelete" CssClass="btn btn-secondary" CommandName="Delete" Text="Yes"/>
<button type="button" class="btn btn-secondary cancel" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<button type="button" data-toggle="modal" data-target="#myModal<%#Eval("MyIDToBound").ToString()%>">
<asp:Label runat="server" ID="lblDeleteButton" Text="Delete"></asp:Label>
</button>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Asp.net using Entity frame work and in grid view when i press delete button it delete the row, and then show this "The object cannot be deleted because it was not found in the ObjectStateManager.""
Here is ascx code :
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="ctrl_ResearcherMyResearch.ascx.cs"
Inherits="ITI.GeoXera.ASP.User_Controls.ctrl_ResearcherMyResearch" %>
<asp:GridView ID="grd_Researcher" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id,Title" DataSourceID="Researcher"
OnRowDeleting="grd_Researcher_RowDeleting"
OnRowEditing="grd_Researcher_RowEditing"
OnRowUpdating="grd_Researcher_RowUpdating" PageSize="3" Width="900px"
AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None"
HorizontalAlign="Center" >
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle"
BackColor="White" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True"
SortExpression="Id" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Title" HeaderText="Title"
SortExpression="Title" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Author" HeaderText="Author"
SortExpression="Author" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="LatitudeFrom" HeaderText="Lat"
SortExpression="LatitudeFrom" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="LongitudeFrom" HeaderText="Long"
SortExpression="LongitudeFrom" />
<asp:BoundField DataField="FkUser" HeaderText="FkUser"
SortExpression="FkUser" Visible="False" ReadOnly="True" />
<asp:BoundField DataField="Link" HeaderText="Link" SortExpression="Link"
/>
<asp:CommandField ButtonType="Button" DeleteText="" InsertText=""
NewText="" SelectText="" ShowEditButton="True" />
<asp:CommandField ButtonType="Button" InsertText="" NewText=""
SelectText="" ShowDeleteButton="True" />
</Columns>
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="30px"
BackColor="#2461BF" Width="20px" Wrap="True" />
<EmptyDataRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="30px"
BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerSettings PageButtonCount="5" />
<PagerStyle VerticalAlign="Middle" BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" VerticalAlign="Middle"
BackColor="#EFF3FB" Font-Strikeout="False" Width="50px" />
<SelectedRowStyle HorizontalAlign="Center" VerticalAlign="Middle"
BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:ObjectDataSource ID="Researcher" runat="server"
DataObjectTypeName="ITI.GeoXera.Model.Models.Research" DeleteMethod="Delete"
InsertMethod="Add" SelectMethod="GetAllBind"
TypeName="ITI.GeoXera.Data.Repositories.ResearchRepository"
UpdateMethod="Update"></asp:ObjectDataSource>
<p>
</p>
<div class="box box-info">
<asp:Panel ID="Panel1" runat="server" GroupingText=" Research Information">
<div class="box-body">
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_Title"
runat="server" Text="Title"></asp:Label>
<div class="col-sm-10">
<asp:TextBox CssClass="form-control" ID="txt_Title"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vldreq_Title" runat="server"
ControlToValidate="txt_Title" ForeColor="#CC0000" ToolTip="Please Enter
Research Title">*</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label ID="lbl_Author" runat="server" CssClass="col-sm-2
control-label" Text="Author"></asp:Label>
<div class="col-sm-10">
<asp:TextBox ID="txt_Author" runat="server"
AutoCompleteType="Disabled" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="vldreq_Author" runat="server"
ErrorMessage="*" ForeColor="#CC0000" ToolTip="Please Enter Author Name"
ControlToValidate="txt_Author"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label ID="lbl_Description" runat="server" CssClass="col-sm-2
control-label" Text="Description"></asp:Label>
<div class="col-sm-10">
<asp:TextBox ID="txt_Description" runat="server"
AutoCompleteType="Disabled" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="vldreq_Description"
runat="server" ErrorMessage="*" ForeColor="#CC0000" ToolTip="Please Enter
Description" ControlToValidate="txt_Description">
</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LatitudeFrom"
runat="server" Text="Latitude From"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LatitudeFrom"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLatFrom" runat="server"
ControlToValidate="txt_LatitudeFrom" ForeColor="#FF3300" ToolTip="Please
Enter
Required Data">*</asp:RequiredFieldValidator>
</div>
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LatitudeTo"
runat="server" Text="Latitude To"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LatitudeTo"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLatTo" runat="server"
ControlToValidate="txt_LatitudeTo" ForeColor="#FF3300" ToolTip="Please Enter
Required Data">*</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LongitudeFrom"
runat="server" Text="Longitude From"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LongitudeFrom"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLongFrom" runat="server"
ControlToValidate="txt_LongitudeFrom" ForeColor="#FF3300" ToolTip="Please
Enter
Required Data">*</asp:RequiredFieldValidator>
</div>
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LongitudeTo"
runat="server" Text="Longitude To"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LongitudeTo"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLongTo" runat="server"
ControlToValidate="txt_LongitudeTo" ForeColor="#FF3300" ToolTip="Please
Enter Required Data">*</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_Link"
runat="server" Text="Link"></asp:Label>
<div class="col-sm-10">
<asp:TextBox CssClass="form-control" ID="txt_Link"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="txt_Link" ForeColor="#FF3300"
ToolTip="Please Enter Link Path">*</asp:RequiredFieldValidator>
</div>
</div>
</div>
<div class="box-footer">
<asp:Button CssClass="btn btn-info pull-right" ID="btn_SaveInfo"
runat="server" Text="Save" OnClick="btn_SaveInfo_OnClick" />
</div>
ascx.cs code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using ITI.GeoXera.Data.InfraStructure;
using ITI.GeoXera.Data.Repositories;
using ITI.GeoXera.Model.Models;
namespace ITI.GeoXera.ASP.User_Controls
{
public partial class ctrl_ResearcherMyResearch : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//grd_Researcher.DataBind();
}
}
protected void grd_Researcher_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
using (UnitOfWork uof = new UnitOfWork())
{
int index = e.RowIndex;
Research research = new Research();
User user = new User();
research.Id = Convert.ToInt32(grd_Researcher.DataKeys[index]
["Id"]);
research.Title = e.NewValues["Title"].ToString();
research.Description = e.NewValues["Description"].ToString();
research.Author = e.NewValues["Author"].ToString();
research.LatitudeFrom =
Convert.ToDouble(e.NewValues["LatitudeFrom"]);
research.LatitudeTo =
Convert.ToDouble(e.NewValues["LatitudeTo"]);
research.LongitudeFrom =
Convert.ToDouble(e.NewValues["LongitudeFrom"]);
research.LongitudeTo =
Convert.ToDouble(e.NewValues["LongitudeTo"]);
research.Link = e.NewValues["Link"].ToString();
research.FkUser = 1;
uof.ResearchRepository.Update(research);
grd_Researcher.EditIndex = -1;
grd_Researcher.DataBind();
uof.Commit();
}
}
protected void grd_Researcher_RowEditing(object sender,
GridViewEditEventArgs e)
{
using (UnitOfWork uof = new UnitOfWork())
{
grd_Researcher.EditIndex = e.NewEditIndex;
grd_Researcher.DataBind();
}
}
protected void grd_Researcher_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
string Title =
Convert.ToString(grd_Researcher.DataKeys[e.RowIndex].Values[1]);
using (UnitOfWork uof = new UnitOfWork())
{
if (Title != null || Title != "")
{
Research research =
uof.ResearchRepository.GetAll().Where(res => res.Title ==
Title).FirstOrDefault();
if (research != null)
{
uof.ResearchRepository.Delete(research);
uof.Commit();
//grd_Researcher.DataSource =
uof.ResearchRepository.GetAllBind();
MessageBox.Show("Deleted successfully.");
}
else
{
MessageBox.Show("Not Found");
}
}
grd_Researcher.EditIndex = -1;
grd_Researcher.DataBind();
}
}
protected void btn_SaveInfo_OnClick(object sender, EventArgs e)
{
using (UnitOfWork uof = new UnitOfWork())
{
User u = new User();
bool entryFound = false;
Research research = new Research();
foreach (GridViewRow row in grd_Researcher.Rows)
{
object val1 = row.Cells[1].Text;
if (val1 != null && val1.ToString() == txt_Title.Text)
{
MessageBox.Show("Entry already exist");
entryFound = true;
break;
}
}
if (!entryFound)
{
research.Title = txt_Title.Text;
research.Author = txt_Author.Text;
research.Description = txt_Description.Text;
research.LatitudeFrom =
Convert.ToDouble(txt_LatitudeFrom.Text);
research.LatitudeTo = Convert.ToDouble(txt_LatitudeTo.Text);
research.LongitudeFrom =
Convert.ToDouble(txt_LongitudeFrom.Text);
research.LongitudeTo =
Convert.ToDouble(txt_LongitudeTo.Text);
research.Link = txt_Link.Text;
research.FkUser = Convert.ToInt32(Session["UserID"]);
uof.ResearchRepository.Add(research);
grd_Researcher.DataBind();
uof.Commit();
MessageBox.Show("Data Added");
foreach (var control in this.Controls)
{
System.Web.UI.WebControls.TextBox tb = control as
System.Web.UI.WebControls.TextBox;
if (tb != null)
{
tb.Text = string.Empty;
}
}
uof.ResearchRepository.GetAllBind();
}
}
}
}
}
Thanks in advance
Are you sure the row you are trying to remove has a value in the "Title". The code you have post withif (Title != null || Title != "") has bug that would allow both null and empty values. It should be if (Title != null && Title != "") if you are trying to prevent that.