Please provide any useful links.
I need to create a sample question types web form in VB.NET which allow user to the following:
The user selects the control type from dropdown (TextBox, RadioButton, ListBox etc).
Generate controls dynamically based on the control type on the webform.
It will always show the TextBox (where user writes the question) and (generated control - TextBox, RadioButton, ListBox etc) and save those values to the database.
Display generated sample questions on the web form.
Thanks.
something like this should work (without database interaction ;)).
aspx:
<asp:DropDownList runat="server" id="TypeDropDown" OnSelectedIndexChanged="OnTypeChanged">
<asp:ListItem>TextBox</asp:ListItem>
<asp:ListItem>RadioButton</asp:ListItem>
</asp:DropDownList>
<asp:Panel>
Question: <asp:TextBox runat="server" ID="Question" /> <br />
Answer: <asp:PlaceHolder runat="server" ID="Place" />
</asp:Panel>
code-behind:
protected override void OnInit(EventArgs eventArgs) {
base.OnInit(eventArgs);
CreateDynamicControl();
}
private void CreateDynamicControl() {
Place.Controls.Clear();
Place.Controls.Add(ControlFactory.Create(TypeDropDown.SelectedValue);
}
private void OnTypeChanged(object sender, EventArgs eventArgs) {
CreateDynamicControl();
}
control factory:
static class ControlFactory {
public static Control Create(string type) {
if ("TextBox".Equals(type))
return new TextBox();
if ("RadioButton".Equals(type))
return new RadioButtonList();
}
}
I think what you are looking for is a DBMS solution where you save in the DB the type of control and than when it is time to show the page you are looking at the type and using a placeholder to generate what you need.
here is a link to wikipedia that explains DBMS : http://en.wikipedia.org/wiki/Database_management_system
I did something similar to this using Declarative syntax, using DataBinding.
Sorry the code is so long, but posting JUST the relevant portion without the nested repeaters might not make sense. I'm posting the full Nested Repeater code for context.
In my setup, this is a survey app, with Question Groups (outside repeater), comprised of one or more Questions (nested repeater).
The relevant portion of how this works is in the nested repeater in the code sample. I had all of the controls available in the markup,. but the .Visible property of each was set based on the QuestionType.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="questiongroup">
<asp:HiddenField runat="server" ID="lblQuestionGroupId" Value='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "QuestionGroupId").ToString()) %>'>
</asp:HiddenField>
<asp:HiddenField runat="server" ID="hfSortOrder" Value='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "SortOrder").ToString()) %>'>
</asp:HiddenField>
<asp:HiddenField runat="server" ID="hdnPointsAwarded" Value='0'></asp:HiddenField>
<br />
<h3><asp:Label runat="server" ID="txtQuestionGroupName" MaxLength="50" Columns="50" Text='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "QuestionGroupName").ToString()) %>'></asp:Label>
</h3>
Score Section
<asp:CheckBox runat="server" ID="chkIsScoreSection" Enabled="false" TabIndex="-1"
Checked='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "IsScoreSection")) %>' />
Minimum required correct answers:
<asp:Label runat="server" ID="lblMinimumForScore" MaxLength="3" Columns="3" Text='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "CommentsRequiredMinimumYesAnswers").ToString()) %>'></asp:Label>
Point Value <asp:Label ID="lblPossiblePoints" runat="server" Text='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "PossiblePoints").ToString()) %>' />
<br />
Group Instructions
<br />
<asp:Label runat="server" ID="lblGroupInstructions" TextMode="MultiLine" Columns="50" Rows="3"
Text='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "GroupInstructions").ToString()) %>'></asp:Label>
<br />
<div class='questionseditor'>
</div>
<br />
<div class="questionsdiv">
<asp:Repeater ID="childRepeater" runat="server" DataSource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("Relation2") %>'>
<ItemTemplate>
<div class="question">
<asp:HiddenField ID="hdnQuestionType" runat="server" Value='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) %>' />
<asp:HiddenField ID="hdnQuestionId" runat="server" Value='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionId\"]").ToString()) %>' />
<asp:HiddenField ID="hfQuestionSortOrder" runat="server" Value='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"SortOrder\"]").ToString()) %>' />
<asp:RequiredFieldValidator SetFocusOnError="True" ID="YesNoForScoreRequiredFieldValidator" runat="server"
ControlToValidate="lstYesNoForScore" Display="Dynamic" ErrorMessage="Required<br />"
Enabled='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "1" %>'></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator SetFocusOnError="True" ID="MemoRequiredFieldValidator" runat="server" ControlToValidate="txtMemoAnswer"
Display="Dynamic" ErrorMessage="Required<br />"
Enabled='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "2" %>'></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator SetFocusOnError="True" ID="NumericAnswerRequiredFieldValidator" runat="server"
ControlToValidate="txtNumericAnswer" Display="Dynamic" ErrorMessage="Required<br />"
Enabled='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "3" %>'></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator SetFocusOnError="True" Display="Dynamic" runat="server" ID="NumericTextRegexValidator"
ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$" Enabled='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "3" %>'
ErrorMessage="*Invalid<br />" ControlToValidate="txtNumericAnswer"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator SetFocusOnError="True" ID="RequiredFieldValidator1" runat="server" ControlToValidate="lstYesNoNonScored"
Display="Dynamic" ErrorMessage="Required<br />" Enabled='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "5" %>'></asp:RequiredFieldValidator>
<asp:Label ID="lblQuestionText" runat="Server" Text='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionText\"]").ToString()) %>'></asp:Label><br />
<asp:RadioButtonList runat="server" ID="lstYesNoForScore" RepeatDirection="Horizontal"
Visible='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "1" %>'>
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No *" Value="0"></asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="txtMemoAnswer" runat="server" Visible='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "2" %>'
TextMode="MultiLine" Rows="3" Width="100%"></asp:TextBox>
<asp:TextBox ID="txtNumericAnswer" runat="server" Visible='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "3" %>'
cols="5"></asp:TextBox>
<uc1:MultipleChoiceControl ID="MultipleChoiceControl1" runat="server" Visible='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "4" %>'
QuestionId='<%# Convert.ToInt32(DataBinder.Eval(Container.DataItem, "[\"QuestionId\"]")) %>' />
<asp:RadioButtonList runat="server" ID="lstYesNoNonScored" RepeatDirection="Horizontal"
Visible='<%# Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment( DataBinder.Eval(Container.DataItem, "[\"QuestionTypeId\"]").ToString()) == "5" %>'>
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
<br />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
Comments for this Question Group (Required if score not awarded)
<asp:TextBox ID="txtGroupComments" runat="server" TextMode="MultiLine" Rows="3" Width="100%"></asp:TextBox>
</div>
</ItemTemplate>
</asp:Repeater>
Related
In my web page, I have an LinkButton inside FooterTemplate, when I Add new row in GridView by using RowCommand. LinkButton do partial postback but my page loses its current scroll position and return scroll to top of the page. How should I maintain my page scroll position when I add new Item in my GridView.
Below is my screen output:
Below is my page code:
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Invoice.aspx.cs" Inherits="RSMS.Users.Invoice" %>
<asp:UpdatePanel ID="upItemDetail" runat="server">
<ContentTemplate>
<asp:GridView
ID="gvItemDetail"
runat="server"
Width="100%"
ShowHeaderWhenEmpty="true"
AutoGenerateColumns="false"
EmptyDataText="No Data Found!"
ShowFooter="False"
BorderStyle="None"
CellPadding="3"
GridLines="Horizontal"
SkinID="AHGridView"
OnRowCommand="gvItemDetail_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Item ID">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtItemName"
runat="server"
placeholder="Item Name"
CssClass="form-control"></asp:TextBox>
</div>
<asp:HiddenField ID="hdnItemID" runat="server" Value="" ClientIDMode="Static" />
<div id="AutoCompleteItem"></div>
<%--<asp:RequiredFieldValidator
ID="rfvItemName"
runat="server"
ControlToValidate="txtItemName"
ErrorMessage="Item Name must be enter."
Display="None">
</asp:RequiredFieldValidator>--%>
<ajaxToolkit:AutoCompleteExtender
ID="acetxtItemName"
runat="server"
ServiceMethod="GetItemID"
ServicePath="~/ApplicationWebService.asmx"
TargetControlID="txtItemName"
MinimumPrefixLength="1"
UseContextKey="false"
CompletionInterval="0"
EnableCaching="true"
CompletionSetCount="30"
FirstRowSelected="true"
CompletionListElementID="AutoCompleteItem"
OnClientItemSelected="ItemSelected">
</ajaxToolkit:AutoCompleteExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtItemName"
runat="server"
placeholder="Item Name"
TabIndex="5"
CssClass="form-control"></asp:TextBox>
</div>
<asp:HiddenField ID="hdnItemID" runat="server" Value="" ClientIDMode="Static" />
<div id="AutoCompleteItem"></div>
<%--<asp:RequiredFieldValidator
ID="rfvItemName"
runat="server"
ControlToValidate="txtItemName"
ErrorMessage="Item Name must be enter."
Display="None">
</asp:RequiredFieldValidator>--%>
<ajaxToolkit:AutoCompleteExtender
ID="acetxtItemName"
runat="server"
ServiceMethod="GetItemID"
ServicePath="~/ApplicationWebService.asmx"
TargetControlID="txtItemName"
MinimumPrefixLength="1"
UseContextKey="false"
CompletionInterval="0"
EnableCaching="true"
CompletionSetCount="30"
FirstRowSelected="true"
CompletionListElementID="AutoCompleteItem"
OnClientItemSelected="ItemSelected">
</ajaxToolkit:AutoCompleteExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sales Price">
<ItemTemplate>
<asp:Label ID="lblItemSalesPrice" runat="server" Text='<%# Eval("Sale_Price") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtSalesPrice"
runat="server"
placeholder="Sales Price"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeSalesPrice" runat="server"
TargetControlID="txtSalesPrice"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvPrice"
runat="server"
ControlToValidate="txtPurchasePrice"
ErrorMessage="Purchase Price must be in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtSalesPrice"
runat="server"
placeholder="Sales Price"
Text='<%# Eval("Sale_Price") == null ? "0" : Eval("Sale_Price") %>'
TabIndex="6"
ClientIDMode="Static"
CssClass="form-control"></asp:TextBox>
<asp:HiddenField ID="hdnPurchase_Price" runat="server" ClientIDMode="Static" Value="0" />
<%--<ajaxToolkit:FilteredTextBoxExtender ID="ftbeSalesPrice" runat="server"
TargetControlID="txtSalesPrice"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>--%>
<%--<asp:RequiredFieldValidator
ID="rfvPurchasePrice"
runat="server"
ControlToValidate="txtPurchasePrice"
ErrorMessage="Purchase Price must be in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item QTY">
<ItemTemplate>
<asp:Label ID="lblItemQTY" runat="server" Text='<%# Eval("Item_Qty") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtItemQuantity"
runat="server"
placeholder="Quantity"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeQuantity" runat="server"
TargetControlID="txtItemQuantity"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvQuantity"
runat="server"
ControlToValidate="txtItemQuantity"
ErrorMessage="Item Quantity must be enter in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtItemQuantity"
runat="server"
placeholder="Quantity"
Text='<%# Eval("Item_Qty") == null ? "0" : Eval("Item_Qty") %>'
TabIndex="7"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeQuantity" runat="server"
TargetControlID="txtItemQuantity"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvQuantity"
runat="server"
ControlToValidate="txtItemQuantity"
ErrorMessage="Item Quantity must be enter in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UOM">
<ItemTemplate>
<asp:Label ID="lblUOM" runat="server" Text='<%# Eval("Item_UOM") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
ID="ddlUOM"
runat="server"
CssClass="ah-border-less"
AutoPostBack="true">
<asp:ListItem Selected="True" Value="0">Select UOM</asp:ListItem>
<asp:ListItem Value="1">GM</asp:ListItem>
<asp:ListItem Value="2">KG</asp:ListItem>
<asp:ListItem Value="3">PCS</asp:ListItem>
<asp:ListItem Value="4">DZ</asp:ListItem>
<asp:ListItem Value="5">BOX</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList
ID="ddlUOM"
runat="server"
TabIndex="8"
CssClass="ah-border-less">
<asp:ListItem Selected="True" Value="0">Select UOM</asp:ListItem>
<asp:ListItem Value="GM">GM</asp:ListItem>
<asp:ListItem Value="KG">KG</asp:ListItem>
<asp:ListItem Value="PCS">PCS</asp:ListItem>
<asp:ListItem Value="DZ">DZ</asp:ListItem>
<asp:ListItem Value="BOX">BOX</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price">
<ItemTemplate>
<asp:Label ID="lblTotalPrice" Text='<%# Eval("Total_Price") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text='<%# Eval("Total_Price") == null ? "0" : Eval("Total_Price") %>'></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="itemAdd" ClientIDMode="AutoID" CommandName="Add" runat="server" TabIndex="9">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
Aspx.cs Code:
protected void gvItemDetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
HiddenField itemID = (HiddenField)gvItemDetail.FooterRow.FindControl("hdnItemID");
HiddenField itemPurchasePrice = (HiddenField)gvItemDetail.FooterRow.FindControl("hdnPurchase_Price");
TextBox itemName = (TextBox)gvItemDetail.FooterRow.FindControl("txtItemName");
TextBox itemSalesPrice = (TextBox)gvItemDetail.FooterRow.FindControl("txtSalesPrice");
TextBox itemQTY = (TextBox)gvItemDetail.FooterRow.FindControl("txtItemQuantity");
DropDownList itemUOM = (DropDownList)gvItemDetail.FooterRow.FindControl("ddlUOM");
Label itemTotalPrice = (Label)gvItemDetail.FooterRow.FindControl("lblTotalPrice");
Decimal dcmTotalPrice = (Convert.ToDecimal(itemSalesPrice.Text.Trim()) * Convert.ToDecimal(itemQTY.Text.Trim()));
Decimal dcmPurchasePrice = (Convert.ToDecimal(itemPurchasePrice.Value.Trim()) * Convert.ToDecimal(itemQTY.Text.Trim()));
DataTable dt = (DataTable)HttpContext.Current.Session["dtInvoiceItemDetail"];
//dt.Rows[0].Delete();
dt.Rows.Add(itemID.Value.Trim(),
itemName.Text.Trim(),
itemSalesPrice.Text.Trim(),
itemQTY.Text.Trim(),
itemUOM.SelectedValue.ToString().Trim(),
dcmTotalPrice,
dcmPurchasePrice
);
dt.AcceptChanges();
gvItemDetail.DataSource = dt;
gvItemDetail.DataBind();
gvItemDetail.Rows[0].Visible = false;
HttpContext.Current.Session["dtInvoiceItemDetail"] = dt;
lblCalculateTotal.Text = (Convert.ToDecimal(dt.AsEnumerable()
.Sum(x => Convert.ToDecimal(x["Total_Price"])))).ToString();
commission = ((Convert.ToDecimal(lblCalculateTotal.Text.Trim()) - Convert.ToDecimal(dt.AsEnumerable()
.Sum(x => Convert.ToDecimal(x["Purchase_Price"])))) * 10) / 100;
}
gvItemDetail.FooterRow.Focus();
}
What I've tried:
Maintain Panel Scroll Position On Partial Postback ASP.NET
Re: Update Panel Scrolling Issue
Maintain Panel Scroll Position On Postback in ASP.NET
page jumps to top
how to retain browser scroll position for Dynamic Control Events
I've found my solution that when I remove gvItemDetail.FooterRow.Focus(); code my page maintain its scroll position. Thanks for all of your comments.
I face this issue before. My resolution is to add maintainScrollPositionOnPostBack="true" in the web.config file
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<pages maintainScrollPositionOnPostBack="true" /> //this will keep current position after postback
</system.web>
In an asp.net web page with a repeater control, how can I avoid a complete page refresh when I select a checkbox in the header to check all checkboxes in the item template rows?
My project is based on asp.net C#, with SQL Server as database.
<asp:Repeater ID="Repeater_product_detail" runat="server" OnItemCommand="Repeater_product_detail_ItemCommand" OnItemDataBound="Repeater_product_detail_ItemDataBound">
<HeaderTemplate>
<table class="table table-striped table-bordered ">
<thead>
<tr>
<td> <asp:CheckBox ID="chk_select" AutoPostBack="true" runat="server" OnCheckedChanged="chk_select_CheckedChanged"/> </td>
<th>SubCategory</th>
<th>Product Name</th>
<th>Product image</th>
<th>Product Price</th>
<th>in stock</th>
<th>Type for</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID="chkDelete" AutoPostBack="true" runat="server" />
<asp:Label ID="lbl_id" Visible="false" runat="server" Text='<%# ("int_product_id") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lbl_sub_cate" runat="server" Text='<%# Eval("txt_sub_category_name") %>'></asp:Label>
<asp:DropDownList ID="ddl_sub_category" Width="100px" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "txt_sub_category_name") %>' runat="server" Visible="false" > </asp:DropDownList>
</td>
<td> <asp:Label ID="lbl_product_name" runat="server" Text='<%# Eval("txt_product_name") %>'></asp:Label>
<asp:TextBox ID="txt_product_name" BackColor="#d4d0c8" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "txt_product_name")%>' Visible="false"></asp:TextBox>
</td>
<td> <%--<asp:Label ID="lbl_product_image" runat="server" Text='<%# Eval("product_img_small") %>'></asp:Label>--%>
<asp:Image ID="Image1" Height="50px" Width="50px" ImageUrl='<%# Eval("product_img_small") %>' runat="server" />
</td>
<td> <asp:Label ID="lbl_product_price" runat="server" Text='<%# Eval("txt_product_price") %>'></asp:Label>
<asp:TextBox ID="txt_product_price" Width="60px" BackColor="#d4d0c8" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "txt_product_price")%>' Visible="false"></asp:TextBox>
</td>
<td> <asp:Label ID="lbl_stock" runat="server" Text='<%# Eval("in_stock") %>'></asp:Label>
<asp:TextBox ID="txt_stock" BackColor="#d4d0c8" Width="60px" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "in_stock")%>' Visible="false"></asp:TextBox>
</td>
<td> <asp:Label ID="lbl_type" runat="server" Text='<%# Eval("cate_type") %>'></asp:Label>
<asp:DropDownList ID="ddl_type" runat="server" Width="60px" DataTextField="cate_type" Visible="false"></asp:DropDownList>
</td>
<td>
<asp:LinkButton ID="lnk_edit" CommandArgument='<%# Eval("int_product_id") %>' CommandName="edit" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="lnk_update" CommandArgument='<%# Eval("int_product_id") %>' Visible="false" CommandName="update" runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="lnk_cancel" CommandArgument='<%# Eval("int_product_id") %>' Visible="false" CommandName="cancel" runat="server">Cancel</asp:LinkButton>
<asp:LinkButton ID="lnk_delete" CommandArgument='<%# Eval("int_product_id") %>' CommandName="delete" OnClientClick='javascript:return confirm("Are you sure you want to delete?")' runat="server">Delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr style="background-color:#15880a">
<td colspan="8">
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:LinkButton ID="lnk_del_selected" CommandArgument='<%# Eval("int_product_id") %>' OnClientClick='javascript:return confirm("Are you sure you want to delete?")' runat="server" OnClick="lnk_del_selected_Click">Deleted Selected</asp:LinkButton>
Behind Code
protected void chk_select_CheckedChanged(object sender, EventArgs e)
{
Control header_control = Repeater_product_detail.Controls[0].Controls[0]; // Find header Template's Items
CheckBox chk = header_control.FindControl("chk_select") as CheckBox;
if (!chk.Checked)
{
toggleCheckState(false);
}
else
{
toggleCheckState(true);
}
}
public void toggleCheckState(bool checkstate)
{
foreach (RepeaterItem item in Repeater_product_detail.Items) // Find Item Template's Items
{
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
CheckBox chk_delete = (CheckBox)item.FindControl("chkDelete");
chk_delete.Checked = checkstate;
}
}
Set AutoPostBack="false" in checkbox properties.
The crux of your question, I believe, is:
"when i select any value from drop down i load some data from database that depends on this selected value, i am facing a problem whenever selection changes page will be refreshed."
There are many ways to accomplish this, but it might require some restructuring to produce the desired effect. A relatively simple way to do this would be:
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:CheckBox ID="chk_select" AutoPostBack="true" runat="server" OnCheckedChanged="chk_select_CheckedChanged"/>
</ContentTemplate>
<Triggers>
<asp:Asyncpostbacktrigger controlid="chk_select" eventname="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
Set the AutoPostBack property to false on the checkbox.
The previous answer was almost correct, except the ASP.NET checkbox doesn't have a SelectedIndexChanged event. It should be CheckedChanged
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:CheckBox ID="chk_select" AutoPostBack="true" runat="server" OnCheckedChanged="chk_select_CheckedChanged"/>
</ContentTemplate>
<Triggers>
<asp:Asyncpostbacktrigger controlid="chk_select" eventname="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
set value of Autopostback attribute of checkbox which causing postback to false
You can set AutoPostBack property of CheckBox to false or else you can also use Ajax UpdatePanel control and put your CheckBox inside it so that whole page will not be reloaded and only checkbox value will be refreshed.
I'm trying to use onclientclick with onclick. The problem is that the page refreshes before any javascript code is run. I'm trying to integrate my javascript code into someone else's code. I know there's a lot of bad coding practices on his code, but I'm required to work with it. If you want me to isolate the code more, I can do that also. I've tried removing onclick and onclientclick. The page still refreshes.
aspx file
Online Checks
<center>
<h2>
Alvey Quality Monitoring Scheme</h2></center>
<div>
<h3>
Every 1/2 hour, check a unit from each line for the following:
Line 1 Global ID
Line 2 Global ID
Lines Running </h3>
<h3>
<asp:DropDownList ID="DropdownList1" runat="server" Height="20px" Width="85px" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="intSKU" DataValueField="strSpec" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select" Value="0" />
</asp:DropDownList><asp:TextBox ID="TextBox1" runat="server" Height="20px" Width="63px" ReadOnly="True"></asp:TextBox><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Nestle1ConnectionString2 %>"
SelectCommand="SELECT [intSKU], [strSpec] FROM [lkpSKUInfo] ORDER BY [intSKU]"></asp:SqlDataSource>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropdownList1"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DropdownList2"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="DropDownList3"></asp:RequiredFieldValidator>
<asp:DropDownList ID="DropdownList2" runat="server"
Height="20px" Width="85px" AutoPostBack="True" DataSourceID="SqlDataSource1" AppendDataBoundItems="true" DataTextField="intSKU" DataValueField="strSpec" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Text="Select" Value="0" />
</asp:DropDownList><asp:TextBox ID="TextBox2" runat="server" Height="20px" Width="63px" ReadOnly="True"></asp:TextBox>
Line 1
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged1" Checked="True" />
Line 2 <asp:CheckBox ID="CheckBox2" runat="server" OnCheckedChanged="CheckBox2_CheckedChanged" AutoPostBack="True" Checked="True" />
</h3>
<h3>
<asp:Label ID="Label1" runat="server" Height="28px" Text="Line 1 Label View " Width="148px"></asp:Label>
<asp:Label ID="Label2" runat="server" Height="28px" Text="Line 2 Label View" Width="148px"></asp:Label></h3>
<p>
<asp:Image ID="Image1" runat="server" Height="155px" Width="670px" />
<asp:Image ID="Image2" runat="server" Height="155px" Width="670px" /></p>
<h3>
<asp:Label ID="Label3" runat="server" Height="28px" Text="Line 1 Print Apply View"
Width="219px"></asp:Label>
<asp:Label ID="Label4" runat="server" Height="28px" Text="Line 2 Print Apply View"
Width="207px"></asp:Label> </h3>
<h3>
<asp:Image ID="Image3" runat="server" Height="155px" Width="670px" />
<asp:Image ID="Image4" runat="server" Height="155px" Width="670px" />
</h3>
<h3>
<asp:Label ID="Label6" runat="server" Height="17px" Text="CASE CODE: " Width="133px"></asp:Label>
<asp:Label ID="Label9" runat="server" Height="17px" Text="Line 1"
Width="108px"></asp:Label>
<asp:Label ID="Label10" runat="server" Height="17px" Text="Line 2"
Width="108px"></asp:Label></h3>
<h3>
<asp:Label ID="Label5" runat="server" Height="39px" Text="Case code must match the line and hour from the can code"
Width="904px"></asp:Label>
<asp:CheckBox ID="CheckBox3" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox3_CheckedChanged" Checked="True" />
<asp:CheckBox ID="CheckBox4" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox4_CheckedChanged" Checked="True" /></h3>
<h3>
<asp:Label ID="Label7" runat="server" Height="17px" Text="SHRINK FILM" Width="122px"></asp:Label> </h3>
<h3>
<asp:Label ID="Label8" runat="server" Height="39px" Text="Shrink Film must be intact, tightly covering the entire case, and have bullseyes that are tight and will not allow a can to fall out" Width="904px"></asp:Label>
<asp:CheckBox ID="CheckBox5" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox5_CheckedChanged" Checked="True" />
<asp:CheckBox ID="CheckBox6" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox6_CheckedChanged" Checked="True" /></h3>
<h3>
<asp:Label ID="Label11" runat="server" Height="17px" Text="LABELS"
Width="122px"></asp:Label> </h3>
<h3>
<asp:Label ID="Label12" runat="server" Height="39px" Text="Labels must be correct for SKU scheduled to be produced, be applied correctly to the cans with no loose, crooked or upside-down labels" Width="904px"></asp:Label>
<asp:CheckBox ID="CheckBox7" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox7_CheckedChanged" Checked="True" />
<asp:CheckBox ID="CheckBox8" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox8_CheckedChanged" Checked="True" /></h3>
<h3>
<asp:Label ID="Label13" runat="server" Height="17px" Text="TRAYS"
Width="122px"></asp:Label></h3>
<h3>
<asp:Label ID="Label14" runat="server" Height="39px" Text="Trays must match product produced, no double case, no loose flaps and no damaged cases" Width="904px"></asp:Label>
<asp:CheckBox ID="CheckBox9" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox9_CheckedChanged" Checked="True" />
<asp:CheckBox ID="CheckBox10" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox10_CheckedChanged" Checked="True" /></h3>
<h3>
<asp:Label ID="Label15" runat="server" Height="17px" Text="PRINT & APPLY"
Width="166px"></asp:Label></h3>
<h3>
<asp:Label ID="Label16" runat="server" Height="39px" Text="Print & Apply stickers must match SKU produced, Julian Date, Best Before Date, Line and Time. Must be legible and applied correctly to the case. Stickers must match DIS ticket (except Australia)" Width="904px"></asp:Label>
<asp:CheckBox ID="CheckBox11" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox11_CheckedChanged" Checked="True" />
<asp:CheckBox ID="CheckBox12" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox12_CheckedChanged" Checked="True" /></h3>
<h3>
<asp:Label ID="Label17" runat="server" Height="17px" Text="DIS TAG"
Width="166px"></asp:Label></h3>
<h3>
<asp:Label ID="Label18" runat="server" Height="39px" Text="Tags must match schedule and product produced" Width="904px"></asp:Label>
<asp:CheckBox ID="CheckBox13" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox13_CheckedChanged" Checked="True" />
<asp:CheckBox ID="CheckBox14" runat="server" Text="OK/Defective" OnCheckedChanged="CheckBox14_CheckedChanged" Checked="True" /></h3><br />
<h3>
Comments:
Operator Number
<asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true" Height="20px" Width="72px" DataSourceID="SqlDataSource2" DataTextField="intOperatorNumber" DataValueField="strLast">
<asp:ListItem Text="Select" Value="No Operator Selected" />
</asp:DropDownList><asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Nestle1ConnectionString2 %>"
SelectCommand="SELECT [intOperatorNumber], [strLast] FROM [tblOperators] ORDER BY [intOperatorNumber]">
</asp:SqlDataSource>
Shift <asp:Label ID="Label" runat="server" Height="20px" Width="53px"></asp:Label>
</h3>
</div>
<asp:TextBox ID="TextBox3" runat="server" Height="81px" Width="381px"></asp:TextBox>
<asp:Label ID="lbl" runat="server" Height="20px" Width="80" BorderWidth="0px" Font-Names="Verdana"></asp:Label>
<input type="text" id="clock" style="border: 0px; width: 80px; height: 20px;" value="" readonly="readonly" />
Specific part of code not working
<!-- the button I'm clicking-->
<asp:Button ID="Button3" Font-Size="15" runat="server" Text="Send Data" Height="40px" Width="245px" OnClientClick="delayer();return false;" OnClick="Button3_Click" />
<asp:Button ID="Button4" Font-Size="15" runat="server" Text="Back" Height="40px" Width="245px" OnClick="Button4_Click" />
</form>
<script type="text/javascript">
</script>
<script type="text/javascript">
/*
var executionTime;
var initialTime = localStorage.getItem("initialTime");
function foo()
{
if(!(initialTime === null)){
executiontime = 5000-(new Date()).getTime() - parseInt(initialTime, 10);
if (executionTime<0) executionTime = 0;
showPopUp(executionTime);
}
}
*/
function showPopUp( var executionTime){
/* if(initialTime=== null)
{
executionTime = 5000;
}
localStorage.setItem("initialTime", (new Date()).getTime());
setTimeout(function() {alert("Warning");
localStorage.setItem("initialTime", null);}, executionTime);
*/
alert("warning");
}
function delayer(){
showPopUp();
}
// constants to define the title of the alert and button text.
var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";
// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
window.alert = function(txt) {
createCustomAlert(txt); //overrides alert method
}
}
function createCustomAlert(txt) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if(d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if(false) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
btn = alertObj.appendChild(d.createElement("a"));
btn.id = "closeBtn";
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
btn.href = "#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function() { removeCustomAlert();return false; }
}
// removes the custom alert from the DOM
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}
</script>
</body>
</html>
You need to return false from delayer function, and also add return to OnClientClick event.
<asp:Button ID="Button3" runat="server" Text="Send Data"
OnClientClick="return delayer();" OnClick="Button3_Click" />
function delayer(){
showPopUp();
return false;
}
I have a datalist filled with items from database and each item has an image button onclick of which I want to show a modalpopup containing the Description of the particular Item. Below is what I have dine so far but fail:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%">
<ItemTemplate>
<table width="228px">
<tr>
<td width="20px" > </td>
<td width="160px" align="center">
<asp:Label ID="pID" runat="server" Visible="false" Text='<%# Eval("id") %>'></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductName") %>' Font-Size="8pt" ForeColor="#336699" Width="100%" />
</td>
<td align="right">
<asp:ImageButton ID="SpecificBtn" ImageUrl="images/SmallCallout.png" OnClick="SpecificBtn_Click" CommandArgument='<%# Eval("Id") %>' runat="server" />
<ajaxToolkit:ModalPopupExtender ID="mdl" runat="server" PopupControlID="pnl" TargetControlID="SpecificBtn" Enabled="True" CancelControlID="btn" DropShadow="true" Drag="True" ></ajaxToolkit:ModalPopupExtender>
</td>
</tr>
</table>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetImage.aspx?id=" + Eval("id") %>' /><br />
<table align="center" style="position:relative; left:2px;" cellspacing="0" cellpadding = "0" width="228px">
<tr>
<td style="background-color:Black;" colspan=2>
<div >
<asp:Image ID="Image2" ImageUrl="/images/cart.png" runat="server" />
<asp:Button CommandName="AddToCart" CssClass="anchor" OnClick="addProduct" CausesValidation="false" CommandArgument='<%# Eval("Id") %>' ID="addToHire" runat="server" Text=" Add To Cart " BackColor="Black" BorderColor="Black" BorderStyle="None" ForeColor="#F8CD20" Height="24" Font-Bold="true" Font-Size="10" />
</div>
</td>
</tr>
</table>
<br /><br />
</ItemTemplate>
<ItemStyle CssClass="dataListItemStyle" HorizontalAlign="Center" VerticalAlign="Top" />
</asp:DataList>
<asp:Panel ID="pnl" runat="server" visible="false" Width="300px" Height="300px" BackColor="red">
<asp:Label ID="Label2" runat="server" Text="Specification"></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Specification") %>'></asp:Label>
<asp:Button ID="btn" runat="server" Text="cancel" />
</asp:Panel>
Code behind:
protected void SpecificBtn_Click(object sender, EventArgs e)
{
DataListItem dli = (DataListItem)((ImageButton)sender).Parent;
ModalPopupExtender ModalPopupExtender2 = (ModalPopupExtender)dli.FindControl("mdl");
pnl.Visible = true;
ModalPopupExtender2.Show();
}
Can somebody tell me how to acheive this and where I went wrong. Thanks.
use jquery..
function onimagebuttonclick()
{
$find('BehaviorIDofmodelpopupextender').show();
}
i hope this solves your problem..
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.