I have a grid view and I wanna update data in the row. I have written a C# code and I've noticed that the RowUpdating event is not firing.
I am using Template Field in my grid. The RowCommand event is working properly, however, the RowUpdating event is not firing.
What should I do? I need your help, please.
The event is like the below:
protected void grdPeople_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
SqlConnection con = new SqlConnection(strCon);
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("InsertUpdatePerson", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#pr_id", Convert.ToInt32(grdPeople.DataKeys[e.RowIndex].Value.ToString()));
com.Parameters.AddWithValue("#pr_name", (grdPeople.FooterRow.FindControl("txtNameFooter") as TextBox).Text.Trim());
com.Parameters.AddWithValue("#pr_gender", (grdPeople.FooterRow.FindControl("rdoMaleFooter") as RadioButton).Checked);
com.Parameters.AddWithValue("#pr_nationality", (grdPeople.FooterRow.FindControl("txtNationalityFooter") as TextBox).Text.Trim());
com.Parameters.AddWithValue("#pr_idn", (grdPeople.FooterRow.FindControl("txtIDnoFooter") as TextBox).Text.Trim());
com.Parameters.AddWithValue("#pr_passport", (grdPeople.FooterRow.FindControl("txtPassportFooter") as TextBox).Text.Trim());
com.Parameters.AddWithValue("#pr_resident", (grdPeople.FooterRow.FindControl("rdoYesFooter") as RadioButton).Checked);
com.Parameters.AddWithValue("#pr_phone", (grdPeople.FooterRow.FindControl("txtPhoneFooter") as TextBox).Text.Trim());
com.Parameters.AddWithValue("#pr_email", (grdPeople.FooterRow.FindControl("txtEmailFooter") as TextBox).Text.Trim());
com.Parameters.Add(new SqlParameter("#ERR_MESSAGE", SqlDbType.NVarChar, 255)).Direction = ParameterDirection.Output;
com.Parameters.Add(new SqlParameter("#ERR_NUMBER", SqlDbType.Int)).Direction = ParameterDirection.Output;
com.ExecuteNonQuery();
int ErrNo = int.Parse(com.Parameters["#ERR_NUMBER"].Value.ToString());
if (ErrNo != 0)
{
lblSuccess.Text = "Data saved successfully.";
grdPeople.EditIndex = -1;
}
else
{
lblError.Text = com.Parameters["#ERR_MESSAGE"].Value.ToString();
}
}
catch (Exception ex)
{
lblSuccess.Text = "";
lblError.Text = ex.Message;
}
}
The below you will find the design of the asp page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ValidationGridView.Default" EnableEventValidation="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Table runat="server">
<asp:TableRow>
<asp:TableCell>
<asp:TextBox runat="server" ID="txtSearch" />
</asp:TableCell>
<asp:TableCell>
<asp:Button runat="server" ID="btnSearch" Text="Search" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
<div>
<asp:GridView ID="grdPeople" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AutoGenerateColumns="false"
OnRowCommand="grdPeople_RowCommand"
OnRowEditing="grdPeople_RowEditing"
OnRowCancelingEdit="grdPeople_RowCancelingEdit"
OnRowUpdating="grdPeople_RowUpdating"
ShowFooter="true" DataKeyNames="pr_id">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("pr_name") %>' ID="lblName" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" Text='<%# Bind("pr_name") %>' runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="Name is required." ForeColor="Red" Text="*" ValidationGroup="Fields" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="txtNameFooter" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtNameFooter" ErrorMessage="Name is required." ForeColor="Red" Text="*" ValidationGroup="FieldsFooter" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_gender") %>' runat="server" ID="lblGender" />
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButton ID="rdoMale" Text ="Male" Checked='<%# Bind("pr_gender_value") %>' GroupName="Gender" runat="server" />
<asp:RadioButton ID="rdoFemale" Text="Female" runat="server" GroupName="Gender" />
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButton ID="rdoMaleFooter" Text="Male" checked="true" runat="server" GroupName="Gender" />
<asp:RadioButton ID="rdoFemaleFooter" Text="Female" runat="server" GroupName="Gender" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nationality">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_nationality") %>' runat="server" ID="lblNationality" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNationality" Text='<%# Bind("pr_nationality") %>' runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="txtNationality" runat="server" ErrorMessage="Nationality is required." ForeColor="Red" Text="*" ValidationGroup="Fields" />
</FooterTemplate>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNationalityFooter" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtNationalityFooter" ErrorMessage="Nationality is required." ForeColor="Red" ValidationGroup="FieldsFooter" Text="*" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID Number">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_idn") %>' runat="server" ID="lblIDNo" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtIDNo" Text='<%# Bind("pr_idn") %>' runat="server" />
<asp:CustomValidator ID="cstIDNo" runat="server" Text="*" ControlToValidate="txtIDNo" ForeColor="Red" ValidateEmptyText="True" ValidationGroup="Fields" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtIDnoFooter" runat="server" />
<asp:CustomValidator ID="cstIDNoFooter" runat="server" Text="*" ControlToValidate="txtIDnoFooter" ForeColor="Red" ValidateEmptyText="True" ValidationGroup="FieldsFooter" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Passport">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_passport") %>' runat="server" ID="lblPassport" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPassport" Text='<%# Bind("pr_passport") %>' runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtPassport" ErrorMessage="Passport is required." ForeColor="Red" ValidationGroup="Fields" Text="*" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtPassportFooter" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtPassportFooter" ErrorMessage="Passport is required." ForeColor="Red" ValidationGroup="FieldsFooter" Text="*" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Resident">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_resident") %>' runat="server" ID="lblResident" />
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButton ID="rdoYes" Text="Yes" Checked='<%# Bind("pr_resident_value") %>' GroupName="Resident" runat="server" />
<asp:RadioButton ID="rdoNo" Text="No" runat="server" GroupName="Resident" />
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButton ID="rdoYesFooter" Text="Yes" Checked="true" GroupName="Resident" runat="server" />
<asp:RadioButton ID="rdoNoFooter" Text="No" runat="server" GroupName="Resident" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_phone") %>' runat="server" ID="lblPhone" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPhone" Text='<%# Bind("pr_phone") %>' runat="server" />
<asp:CustomValidator ID="cstPhone" runat="server" Text="*" ControlToValidate="txtPhone" ForeColor="Red" ValidateEmptyText="True" ValidationGroup="Fields" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtPhoneFooter" runat="server" />
<asp:CustomValidator ID="cstPhoneFooter" runat="server" Text="*" ControlToValidate="txtPhoneFooter" ForeColor="Red" ValidateEmptyText="True" ValidationGroup="FieldsFooter" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label Text='<%# Bind("pr_email") %>' runat="server" ID="lblEmail" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmail" Text='<%# Bind("pr_email") %>' runat="server" />
<asp:CustomValidator ID="cstEmail" runat="server" Text="*" ControlToValidate="txtEmail" ForeColor="Red" ValidateEmptyText="True" ValidationGroup="Fields" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmailFooter" runat="server" />
<asp:CustomValidator ID="cstEmailFooter" runat="server" Text="*" ControlToValidate="txtEmailFooter" ForeColor="Red" ValidateEmptyText="True" ValidationGroup="FieldsFooter" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ImageUrl="~/icons/edit.png" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton runat="server" ImageUrl="~/icons/delete.png" CommandName="Delete" ToolTip="Delete" Width="20px" Height="20px" />
<asp:ImageButton runat="server" ImageUrl="~/icons/email.png" CommandName="Mail" ToolTip="Mail" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton runat="server" ImageUrl="~/icons/save.png" CommandName="Save" ToolTip="Save" Width="20px" Height="20px" ValidationGroup="Fields"/>
<asp:ImageButton runat="server" ImageUrl="~/icons/cancel.png" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton runat="server" ID="btnInsert" ImageUrl="~/icons/add.png" ValidationGroup="FieldsFooter" CommandName="Insert" ToolTip="Insert" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label runat="server" ID="lblSuccess" ForeColor="Green" />
<br />
<asp:Label runat="server" ID="lblError" ForeColor="Red" />
</div>
<div>
<asp:ImageButton ID="btnImportExl" runat="server" ImageUrl="~/icons/excel.png" Width="40px" Height="40px" />
</div>
<div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" ValidationGroup="Fields" />
</div>
</form>
</body>
</html>
I added the grid design above to show you how I designed it and how I set its properties.
Thank you.
In your GridView's EditItemTemplate, you miss out a button with CommandName="Update" which this button will trigger the grdPeople_RowUpdating event.
<EditItemTemplate>
<asp:ImageButton runat="server" ImageUrl="~/icons/save.png" CommandName="Save" ToolTip="Save" Width="20px" Height="20px" ValidationGroup="Fields"/>
<asp:ImageButton runat="server" ImageUrl="~/icons/cancel.png" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
SOLUTION
Change the Save button CommandName's value from CommandName="Save" to CommandName="Update".
<EditItemTemplate>
<asp:ImageButton runat="server" ImageUrl="~/icons/save.png" CommandName="Update" ToolTip="Save" Width="20px" Height="20px" ValidationGroup="Fields"/>
<asp:ImageButton runat="server" ImageUrl="~/icons/cancel.png" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
REFERENCE
Edit and Update Record in GridView in ASP.Net
Related
I am trying to follow this exemple https://www.aspsnippets.com/Articles/Transfer-Selected-Rows-from-one-GridView-to-Another-in-Asp.net.aspx however my version dose not refreash the page when a checkbox is checked why is that?
Here is my front end code,
<asp:GridView ID="gvPurchases" runat="server" AutoGenerateColumns="false" ShowFooter="true" onrowdatabound="gvPurchases_RowDataBound"
ShowHeaderWhenEmpty="true" AllowPaging="True" OnPageIndexChanging="gridView_PageIndexChanging" DataKeyNames="compras_id"
OnRowCommand="gvPurchases_RowCommand" OnRowEditing="gvPurchases_RowEditing" OnRowCancelingEdit="gvPurchases_RowCancelingEdit"
OnRowUpdating="gvPurchases_RowUpdating" CellPadding="3" AllowUserToResizeColumns="True" PageSize="5" AllowSorting="true" onsorting="gvPurchases_Sorting" GridLines="None" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<PagerSettings Mode="Numeric" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRow" AutoPostBack="true" EnableViewState="true" runat="server" onclick = "Check_Click(this)" OnCheckedChanged="CheckBox_CheckChanged" />
<%--<asp:CheckBox ID="chkRow" runat="server" />--%>
<asp:ImageButton ImageUrl="~/Images/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px"/>
<asp:ImageButton ImageUrl="~/Images/delete.png" runat="server" CommandName="Delete" ToolTip="Delete" Width="20px" Height="20px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/Images/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px"/>
<asp:ImageButton ImageUrl="~/Images/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/Images/addnew.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compras ID" SortExpression="compras_id">
<ItemTemplate>
<asp:Label DataField="compras_id" ID="lblPurschaseID" CssClass="gridTextbox" Text='<%# Eval("compras_id") %>' runat="server" />
</ItemTemplate>
<%--<EditItemTemplate>
<asp:TextBox CssClass="gridTextbox" ID="txtType" Text='<%# Eval("tipo") %>' runat="server" />
</EditItemTemplate>--%>
<FooterTemplate>
<asp:TextBox CssClass="gridTextbox" ID="txtPurschaseIDFooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contract Number" >
<ItemTemplate>
<asp:Label DataField="numero_contrato" ID="lblContractNumber" CssClass="gridTextbox" Text='<%# Eval("numero_contrato") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drGridContractID" Runat="server" AutoPostBack="false" OnSelectedIndexChanged="DropDown_SelectedIndexChanged" />
<%-- <asp:TextBox CssClass="gridTextbox" ID="txtSupplier" Text='<%# Eval("nombre_proveedor") %>' runat="server" />--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox CssClass="gridTextbox" ID="txtContractNumberFooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
And here is my backend:
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
However the page does not refresh when checkbox is checked why is that?
I had to remove onclick = "Check_Click(this)" to fix the proble the onClick is useless.
Change
<asp:CheckBox ID="chkRow" AutoPostBack="true" EnableViewState="true" runat="server" onclick = "Check_Click(this)" OnCheckedChanged="CheckBox_CheckChanged" />
to
<asp:CheckBox ID="chkRow" AutoPostBack="true" EnableViewState="true" runat="server" OnCheckedChanged="CheckBox_CheckChanged" />
can anyone tell me what i am missing why my row editing event is not firing.
I am trying to give edit facility in same grid as well as Add new data.
I am able to add new data (new row) but unable to edit existing row for update.
my row editing event is not firing.
<asp:GridView ID="grdHierarchy" runat="server" AllowSorting="True" AutoGenerateColumns="False" CssClass="tableGridBorder" GridLines="None" ShowFooter="True" ShowHeaderWhenEmpty="True" Width="100%" OnRowCommand="grdHierarchy_RowCommand" OnRowDataBound="grdHierarchy_RowDataBound"
OnRowEditing="grdHierarchy_RowEditing">
<AlternatingRowStyle CssClass="AlternateRow" />
<Columns>
<asp:TemplateField HeaderText="Sr.#">
<ItemTemplate>
<asp:Label ID="lblSrNo" runat="server" Text="<%# Container.DataItemIndex + 1 %>"></asp:Label>
</ItemTemplate>
<ItemStyle CssClass="textAlignCenter" />
<HeaderStyle CssClass="textAlignCenter" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RequiredFieldValidator ID="rfvHierarchyName" runat="server" SetFocusOnError="True" ControlToValidate="txtHierarchyName" ErrorMessage="Enter Reference." ValidationGroup="grpHierarchy">
<asp:TextBox ID="txtHierarchyName" CssClass="textBoxSmall" Style="visibility: visible" runat="server" Text='<%# Bind("Name") %>' MaxLength="50"></asp:TextBox>
</asp:RequiredFieldValidator>
<span style="color: Red;">*</span>
<asp:RegularExpressionValidator ID="regexValiator3" runat="server" ControlToValidate="txtAPReference" ErrorMessage='Invalid Reference.' Display="None" ValidationGroup="grpHierarchy" ValidationExpression='([^<>\"\^])*'>
</asp:RegularExpressionValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:RequiredFieldValidator ID="rfvHierarchyName" runat="server" SetFocusOnError="True" ControlToValidate="txtHierarchyName" ErrorMessage="Enter Reference." ValidationGroup="grpfHierarchy">
<asp:TextBox ID="txtHierarchyName" CssClass="textBoxSmall" Style="visibility: visible" runat="server" Text='<%# Bind("Name") %>' MaxLength="50"></asp:TextBox>
</asp:RequiredFieldValidator>
<span style="color: Red;">*</span>
<asp:RegularExpressionValidator ID="regexValiator4" Display="None" runat="server" ControlToValidate="txtHierarchyName" ErrorMessage='Invalid Reference.' ValidationGroup="grpfHierarchy" ValidationExpression='([^<>\"\^])*'>
</asp:RegularExpressionValidator>
</FooterTemplate>
<ItemStyle CssClass="textAlignLeft" />
<HeaderStyle CssClass="textAlignLeft" />
<FooterStyle CssClass="textAlignLeft" />
</asp:TemplateField>
<asp:TemplateField HeaderText="LevelName">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Level.Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RequiredFieldValidator ID="rfvLevelName" runat="server" SetFocusOnError="True" ControlToValidate="ddlLevelName" ErrorMessage="Select Level Number." Width="100px" CssClass="redborderlarge" ValidationGroup="grpHierarchy" InitialValue="--Select--">
<asp:DropDownList ID="ddlLevelName" Width="200px" Style="visibility: visible" runat="server">
</asp:DropDownList>
</asp:RequiredFieldValidator><span style="color: Red; margin-top: 4px;">*</span>
</EditItemTemplate>
<FooterTemplate>
<asp:RequiredFieldValidator ID="rfvCustomerName" runat="server" SetFocusOnError="True" ControlToValidate="ddlLevelName" ErrorMessage="Select Customer." ValidationGroup="grpfHierarchy" InitialValue="--Select--">
<asp:DropDownList ID="ddlLevelName" Width="200px" Style="visibility: visible" runat="server">
</asp:DropDownList>
</asp:RequiredFieldValidator><span style="color: Red;">*</span>
</FooterTemplate>
<ItemStyle CssClass="textAlignLeft" />
<HeaderStyle CssClass="textAlignLeft" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btnHierarchyEdit" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnHierarchyUpdate" runat="server" CommandName="Select" Text="Update" CausesValidation="true" ValidationGroup="grpfHierarchy" OnClick="btnHierarchyUpdate_Click" OnClientClick="return ToggleCursor2(1,'grpAP',true);"></asp:LinkButton>
<asp:LinkButton ID="btnHierarchyCancel" runat="server" CausesValidation="false" CommandName="Select" Text="Cancel" OnClick="btnHierarchyCancel_Click"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="btnHierarchyAdd" runat="server" CausesValidation="true" ValidationGroup="grpfHierarchy" CommandName="New" Text="Add" OnClientClick="return true;"></asp:LinkButton>
</FooterTemplate>
<ItemStyle CssClass="textAlignCenter" />
<HeaderStyle CssClass="textAlignCenter" />
<FooterStyle CssClass="textAlignCenter" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="Header" />
<RowStyle CssClass="Row" />
<FooterStyle CssClass="Header borderBttm" />
</asp:GridView>
and my code behind code is this event is not firing.where I am wrong
protected void grdHierarchy_RowEditing(object sender, GridViewEditEventArgs e)
{
grdHierarchy.EditIndex = e.NewEditIndex;
grdHierarchy.ShowFooter = false;
}
protected void grdHierarchy_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("New"))
{
Hierarchy Hierarchy = new Hierarchy();
TextBox txtHierarchyName = (TextBox)grdHierarchy.FooterRow.FindControl("txtHierarchyName");
DropDownList ddlLevelName = (DropDownList)grdHierarchy.FooterRow.FindControl("ddlLevelName");
string HierarchyName = txtHierarchyName.Text.Trim();
bool IsNameExist = Hierarchy.IsNameExist(Session, HierarchyName);
if (IsNameExist == false)
{
Hierarchy.Id = 0;
Hierarchy.Name = HierarchyName;
Hierarchy.LevelId = Convert.ToInt64(ddlLevelName.SelectedValue);
Hierarchy.CreatedDtTm = DateTime.Now;
Hierarchy.ModifiedDtTm = DateTime.Now;
Hierarchy.Save(Session);
fillHierarchyGrid();
}
else
{
cGlobalUI.showPopupMsg(Page, "Hierarchy Name is already Exist", cGlobalUI.MessageType.mtInformation);
}
}
}
I Have made a popup box to display Row event on click and it displays the details in the Row,But I dont want to dispaly the box on clicking Insert/Edit/Delete Button which is inside the Gridview. For this I have used jquery .
Here is my Code
$(function () {
var grid = document.getElementById('<%= gvDetails.ClientID%>');
$('tr', grid).on('click', function (obj, b) {
if (['Update', 'Edit', 'Add'].indexOf(obj.target.type) == "image")
return true;
else
$("#id").html($(".clsempid", $(this).closest("tr")).html());
$("#name").html($(".clsempid1", $(this).closest("tr")).html());
$("#department").html($(".clsempid2", $(this).closest("tr")).html());
$("#age").html($(".clsempid3", $(this).closest("tr")).html());
$("#sal").html($(".clsempid4", $(this).closest("tr")).html());
$("#dialog").dialog({
title: "View Details",
buttons: {
Ok: function () {
$(this).dialog('close');
}
},
modal: true
});
});
});
<asp:TemplateField HeaderText="Edit/Delete" HeaderStyle-Width="5%">
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Images/update.png" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/cancel.png" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Insert.png" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.png" ToolTip="Delete" Height="10px" Width="10px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/Add.png" CommandName="Add" Width="20px" Height="20px" ToolTip="Add new User" ValidationGroup="validaiton" OnClientClick="GetGridFooterRowvalues()" />
</FooterTemplate>
</asp:TemplateField>`<asp:GridView ID="gvDetails" style="background-color:lightgreen; border-collapse: collapse;
background-color: lightgreen;
margin-top: -53px;" DataKeyNames="EmpId,EmpName" runat="server"
AutoGenerateColumns="false" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="white"
CellPadding="10" CellSpacing="0"
AllowPaging="true" PageSize="5"
OnRowCommand="gvDetails_RowCommand" OnRowUpdating="gvDetails_RowUpdating"
OnRowEditing="gvDetails_RowEditing" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowDeleting="gvDetails_RowDeleting" OnPageIndexChanging="OnPaging"
OnSelectedIndexChanged="OnSelectedIndexChanged" AllowSorting="True" OnRowDataBound="gvDetails_OnRowDataBound">
<Columns >
<asp:TemplateField HeaderText="EmployeeID">
<ItemTemplate>
<asp:Label ID="lblempid" runat="server" class="clsempid"
Text='<%# Eval("EmpId")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtempid" onkeypress=" return numeric(event,this);"
MaxLength="5" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvempid" runat="server" ControlToValidate="txtempid" Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmployeeName">
<EditItemTemplate>
<asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("EmpName") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblempname" runat="server" class="clsempid1" Text='<%#Eval("EmpName") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtempname1" runat="server" AutoPostBack="false" onkeypress=" return onlyAlphabets(event,this);" />
<asp:RequiredFieldValidator ID="rfvempname" runat="server" ControlToValidate="txtempname1" Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<EditItemTemplate>
<asp:TextBox ID="txtdep" runat="server" Text='<%#Eval("Dep") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbldep" runat="server" class="clsempid2" Text='<%#Eval("Dep") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtdep1" runat="server" />
<asp:RequiredFieldValidator ID="rfvdep" runat="server" ControlToValidate="txtdep1" Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<HeaderTemplate>
Age
<br></br>
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtage" runat="server" Text='<%#Eval("Age") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblage" runat="server" class="clsempid3" Text='<%#Eval("Age") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtage1" runat="server" MaxLength="3" onkeypress=" return numeric(event,this);" ErrorMessage="*" ControlToValidate="txtage1" onchange="handleChange(this);" />
<asp:RequiredFieldValidator ID="rfvage" runat="server" ControlToValidate="txtage1" ErrorMessage="*" ValidationGroup="validaiton" />
</EditItemTemplate>
</FooterTemplate>
</asp:TemplateField>`
have you tried putting your code between {}.
var grid = document.getElementById('<%= gvDetails.ClientID%>');
$('tr', grid).on('click', function (obj, b) {
if (['Update', 'Edit', 'Add'].indexOf(obj.target.type) == "image"){
return true;
}else{
$("#id").html($(".clsempid", $(this).closest("tr")).html());
$("#name").html($(".clsempid1", $(this).closest("tr")).html());
$("#department").html($(".clsempid2", $(this).closest("tr")).html());
$("#age").html($(".clsempid3", $(this).closest("tr")).html());
$("#sal").html($(".clsempid4", $(this).closest("tr")).html());
$("#dialog").dialog({
title: "View Details",
buttons: {
Ok: function () {
$(this).dialog('close');
}
},
modal: true
});
}
});
});
I am trying to design gridview inside gridview with insert update and delete but in this i cant insert record. Can anyone Help?
Here is database table
1) tbl_SShow(ShowTimeId{P-Auto inc.},TheatreId,MovieId,FromDate,ToDate)
2) tbl_Show(ShowID{P-Auto inc.},ShowTime,Silver,Gold, Platinum,ShowTimeId)
3) tbl_Theatre(TheatreId{P-Auto inc.}, TName, Taddress)
and here is aspx page
<!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 runat="server">
<script language=javascript type="text/javascript">
function expandcollapse(obj,row)
{
var div = document.getElementById(obj);
var img = document.getElementById('img' + obj);
if (div.style.display == "none")
{
div.style.display = "block";
if (row == 'alt')
{
img.src = "minus.gif";
}
else
{
img.src = "minus.gif";
}
img.alt = "Close to view other Customers";
}
else
{
div.style.display = "none";
if (row == 'alt')
{
img.src = "plus.gif";
}
else
{
img.src = "plus.gif";
}
img.alt = "Expand to show Orders";
}
}
</script>
</head>
<body>
<form id="AddEventForm" runat="server">
<ul id="tabsmenu1" class="tabsmenu">
<li class="active">Add Show Time</li>
</ul>
<div class="form">
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="#f1f1f1"
AutoGenerateColumns=false DataSourceID="SqlDataSource1" DataKeyNames="MovieID"
GridLines=None OnRowDataBound="GridView1_RowDataBound"
OnRowCommand = "GridView1_RowCommand" OnRowUpdating = "GridView1_RowUpdating" BorderStyle=Outset
OnRowDeleting = "GridView1_RowDeleting" OnRowDeleted = "GridView1_RowDeleted"
OnRowUpdated = "GridView1_RowUpdated" AllowSorting=true
Width="80%" >
<RowStyle BackColor="Gainsboro" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#0083C1" ForeColor="White"/>
<FooterStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:expandcollapse('div<%# Eval("ShowTimeId") %>', 'one');">
<img id="imgdiv<%# Eval("ShowTimeId") %>" alt="Click to show/hide Orders for Customer <%# Eval("ShowTimeId") %>" width="9px" border="0" src="../images/plus.gif"/>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theatre Id" SortExpression="TheatreId">
<ItemTemplate>
<asp:Label ID="lblShowTimeId" Text='<%# Eval("ShowTimeId") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblShowTimeId" Text='<%# Eval("ShowTimeId") %>' runat="server"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theatre Id" SortExpression="TheatreId">
<ItemTemplate>
<asp:Label ID="lblTheatreId" Text='<%# Eval("TheatreId") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTheatreId" Text='<%# Eval("TheatreId") %>' runat="server"></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTheatre" runat="server" CssClass="form_input" AutoPostBack="True" TabIndex="1">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie Id" SortExpression="MovieId">
<ItemTemplate><%# Eval("MovieId")%></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlMovie" runat="server" CssClass="form_input" AutoPostBack="True" TabIndex="2">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlMovie" runat="server" CssClass="form_input" AutoPostBack="True" TabIndex="2">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="From Date" SortExpression="FromDate">
<ItemTemplate><%# Eval("FromDate")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFromDate" Text='<%# Eval("FromDate") %>' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtFromDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
</asp:CalendarExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFromDate" Text='' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtFromDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
</asp:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To Date" SortExpression="ToDate">
<ItemTemplate><%# Eval("ToDate")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtToDate" Text='<%# Eval("ToDate") %>' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="txtToDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton2">
</asp:CalendarExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtToDate" Text='' runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/cal/calendar.gif" AlternateText="Click to show calendar" TabIndex="3" />
<asp:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="txtToDate" Format="dd/MM/yyyy" PopupButtonID="ImageButton2">
</asp:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="linkDeleteShow" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkAddShow" CommandName="AddShow" runat="server">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("ShowTimeId") %>" style="display:none;position:relative;left:15px;OVERFLOW: auto;WIDTH:97%" >
<asp:GridView ID="GridView2" AllowPaging="True" AllowSorting="true" BackColor="White" Width=100% Font-Size=X-Small
AutoGenerateColumns="false" Font-Names="Verdana" DataKeyNames="ShowTimeId" runat="server" ShowFooter="true"
OnPageIndexChanging="GridView2_PageIndexChanging" OnRowUpdating = "GridView2_RowUpdating" CssClass="Gridview"
OnRowCommand = "GridView2_RowCommand" OnRowEditing = "GridView2_RowEditing" GridLines=None
OnRowUpdated = "GridView2_RowUpdated" OnRowCancelingEdit = "GridView2_CancelingEdit" OnRowDataBound = "GridView2_RowDataBound"
OnRowDeleting = "GridView2_RowDeleting" OnRowDeleted = "GridView2_RowDeleted" OnSorting = "GridView2_Sorting"
BorderStyle=Double BorderColor="#0083C1">
<RowStyle BackColor="Gainsboro" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#0083C1" ForeColor="White"/>
<FooterStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Show ID" SortExpression="ShowID">
<ItemTemplate>
<asp:Label ID="lblShowID" Text='<%# Eval("ShowID") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblShowID" Text='<%# Eval("ShowID") %>' runat="server"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShowTime" SortExpression="ShowTime">
<ItemTemplate><%# Eval("ShowTime")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtShowTime" Text='<%# Eval("ShowTime")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtShowTime" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Silver" SortExpression="Silver">
<ItemTemplate><%# Eval("Silver")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtSilver" Text='<%# Eval("Silver")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSilver" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gold" SortExpression="Gold">
<ItemTemplate><%# Eval("Gold")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGold" Text='<%# Eval("Gold")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGold" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Platinum" SortExpression="Platinum">
<ItemTemplate><%# Eval("Platinum")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPlatinum" Text='<%# Eval("Platinum")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtPlatinum" Text='' runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="linkDeleteCust" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkAddOrder" CommandName="AddShow" runat="server">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Event_MovieConnectionString %>"
SelectCommand="SELECT s.[ShowTimeId], s.[TheatreId], s.[MovieId], s.[FromDate], s.[ToDate], s.[Created],
s.[Modified] FROM [tbl_SShow] s ORDER BY s.[ShowTimeId]">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Please give me a solutions
Thanks.
Is there a way were I could generate a message box if a record exist in the database after the user clicked the insert link button? I want the formview to check if record exist if not make an insert.
Help would be much appreciated.
Thanks in advance :)
Here's a sample of my code:
Manage Books
Add/Remove Books
Note: For the book ID/ISBN please refer to the barcode in the ISBN, usually located
at the back of the book. A barcode reader is required.
<EditItemTemplate>
Book ID/ISBN:
<asp:Label ID="bookidLabel1" runat="server" Text='<%# Eval("bookid") %>' />
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<br />
Category:
<asp:TextBox ID="categoryidTextBox" runat="server"
Text='<%# Bind("categoryid") %>' />
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>' />
<br />
Status:
<asp:TextBox ID="statusidTextBox" runat="server"
Text='<%# Bind("statusid") %>' />
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<br />
name:
<asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
Book ID:
<asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>' />
<asp:RequiredFieldValidator ID="RequesFieldValidator1" runat="server" ErrorMessage="* Required" ControlToValidate="bookidTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator" runat="server" Display="Dynamic" ControlToValidate="bookidTextBox" ValidationExpression="^([\S\s]{13,13})$" ErrorMessage="Invalid ID/ISBN. Please try again" ValidationGroup="InsertBook">
</asp:RegularExpressionValidator>
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="* Required" ControlToValidate="booktitleTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="* Required" ControlToValidate="lastnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="* Required" ControlToValidate="firstnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="* Required" ControlToValidate="descriptionTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Category:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="categoryDataSource" DataTextField="name"
DataValueField="categoryid" SelectedValue='<%# Bind("categoryid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="categoryDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
</asp:SqlDataSource>
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>'/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="* Required" ControlToValidate="dateaddedTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<%--<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="dateaddedTextBox" ErrorMessage="RegularExpressionValidator"
ValidationExpression="(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])">
</asp:RegularExpressionValidator>--%>
<br />
Status:
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="statusDataSource" DataTextField="statusname"
DataValueField="statusid" SelectedValue='<%# Bind("statusid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="statusDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
</asp:SqlDataSource>
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="* Required" ControlToValidate="quantityTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Add" ValidationGroup="InsertBook"/>
<asp:Button ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
<EmptyDataTemplate>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</EmptyDataTemplate>
<HeaderTemplate>
Add a new book
</HeaderTemplate>
</asp:FormView>
You can check in the ItemInserting method.
Something like:
void FormViewName_ItemInserting(object sender, FormViewInsertEventArgs e)
{
string somevalue = e.Values["somefieldtoget"];
//make your calls to the DB to check the somevalue doesn't exist
if(exists)
e.Cancel = true;
}
You can also do this on the data sources Inserting Method (sql datasource assumed) as well....
void datasourcename_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
...
}
Another approach as mentioned by #steve-wellens is if you have a primary key that is based on one or more of the fields in the form view (not an auto generated number then below will work great for catching an attempt to insert a duplicate key/record.
void FormViewName_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
if (e.Exception != null)
{
if (((SqlException)e.Exception).Number == 2627)
{
e.ExceptionHandled = true;
e.KeepInInsertMode = true;
// Display error message.
}
}
}
It would be better to put a unique index on the table and catch exceptions that occur when an attempt is made to insert a duplicate record.
It's the simplest way to ensure integrity. Otherwise you have to start a read transaction to handle the case where between the time you check and the time you insert, some other process is doing the exact same thing.