Currently, I'm trying to insert a new item into a drop-down list. It seems like nothing is working. Nothing is added to the dropdown list. It finds the control find I belive but does not insert a new item. Is my syntax off or something?
protected void livFact_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListViewItem item = livFact.Items[e.NewEditIndex];
DropDownList ddl = (DropDownList)item.FindControl("ddlLocation");
ddl.Items.Insert(0, new ListItem("--Location--", "0"));
}
<%--Edit Item Template--%>
<EditItemTemplate>
<tr>
<td>
<asp:Button runat="server" ID="btnModifySave" SkinID="btnListView" class="btn btn-success btn-sm" CausesValidation="true" CommandName="Update" Text="Save" ValidationGroup="ModifySave" />
<asp:Button runat="server" ID="btnModifyCancel" SkinID="btnListView" class="btn btn-danger btn-sm" CausesValidation="false" CommandName="Cancel" Text="Cancel" />
</td>
<%--Copy Area Start Set Enabled="true" --%>
<td>
<asp:DropDownList runat="server" ID="ddlLocation" class="form-control" Enabled="true" DataSourceID="sdsDropDownListLocation" DataTextField="Location" DataValueField="LocationID" AppendDataBoundItems="true" />
<asp:Label runat="server" ID="lblLocationID" Visible="false" Text='<%# Bind("LocationID") %>' />
<br />
<div class="alert alert-warning rounded">
<asp:Label runat="server" Text="Current Location editing: " />
<asp:Label runat="server" CssClass="text-primary font-weight-bold" ID="lblLocation" Text='<%# Bind("Location") %>' />
</div>
</td>
<td class="text-center">
<asp:TextBox runat="server" ID="txtFact" class="form-control" Enabled="true" Text='<%# Bind("Fact") %>' TextMode="MultiLine" Rows="5" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtFact" Enabled="true" Display="Dynamic" ErrorMessage="A Fact is required." Text="*" ForeColor="Red" SetFocusOnError="true" ValidationGroup="ModifySave" />
</td>
<%-- Copy Area End--%>
</tr>
</EditItemTemplate>
I found a simpler approach to solve my problem. Instead of using the code behind and c#, you can solve the problem on the aspx page itself. You can simply add a ListItem and put anything you want into the drop-down list on top of any data your binding to the drop-down list from a database. I would then suggest creating a Required Field Validator with an Initial Value to stop it from saving to the database if the user clicks save with the default option selected.
<asp:DropDownList runat="server" ID="ddlLocation" class="form-control" Enabled="true" DataSourceID="sdsDropDownListLocation" DataTextField="Location" DataValueField="LocationID" AppendDataBoundItems="true">
<asp:ListItem Text="--Location--" Value="-1" Selected="True" />
</asp:DropDownList>
Found my answers here.
Related
I have created a student enrolment wizard that they go through every year that uses the MultiView control and I have multiple View Controls within it. An example of one View control can be seen below;
<asp:View ID="address_view" runat="server">
<h1>Address:</h1>
<asp:Button ID="add_new_address" CssClass="blue" runat="server" Text="Add New Address" OnClick="add_new_address_Click" />
<div id="add_address_div" runat="server">
<asp:DropDownList ID="address_dropdown_insert" runat="server">
<asp:ListItem Value="Home">Home Address</asp:ListItem>
<asp:ListItem Value="Term">Term Time Address</asp:ListItem>
<asp:ListItem Value="Mail">Mail Address</asp:ListItem>
<asp:ListItem Value="Business">Business Address</asp:ListItem>
</asp:DropDownList><br />
Address 1:
<asp:TextBox Text="" runat="server" ID="address_1TextBox" /><br />
Address 2:
<asp:TextBox Text="" runat="server" ID="address_2TextBox" /><br />
Town/City:
<asp:TextBox Text="" runat="server" ID="town_cityTextBox" /><br />
County:
<asp:TextBox Text="" runat="server" ID="countyTextBox" /><br />
PostCode:
<asp:TextBox Text="" runat="server" ID="postcodeTextBox" /><br />
Country:
<asp:TextBox Text="" runat="server" ID="countryTextBox" />
<asp:Button runat="server" CommandName="Insert" Text="Insert" ID="InsertButton" OnClick="insert_address_button_Click" />
<asp:Button runat="server" CommandName="Cancel" Text="Clear" ID="Button4" OnClick="cancel_address_button_Click" /><br />
</div>
<asp:ListView ID="address_list" runat="server" DataSourceID="user_address" DataKeyNames="address_id">
<EditItemTemplate>
// code here
</EditItemTemplate>
<EmptyDataTemplate>
<br />
<p>There are currently no addresses found, please click the button above to add a new address.</p>
</EmptyDataTemplate>
<ItemTemplate>
//code here
</ItemTemplate>
<LayoutTemplate>
//code here
</LayoutTemplate>
</asp:ListView>
<br />
<asp:Button CommandName="NextView" ID="Button1" Enabled="false" runat="server" Text="Next" />
</asp:View>
I have the following C# on PageLoad
protected void Page_Load(object sender, EventArgs e)
{
Button1.Enabled = address_list.Items.Any();
}
However, the button still appears even if there is no data in the ListView.
My question is, how can I prevent a user from continuing onto the next view when they click Button1 if their is no data in the ListView?
I'm fairly new to C# so any help would be much appreciated.
Try something like:
if(address_list.Items.Count() = 0)
{
Button1.enabled = false
}else
{
Button1.enabled = true
}
But have in mind that if you call this before you bind the data it wont work so be sure to not use this code as the first line in the Page load event
The lv.items.Count() will return 0 if it has no rows after binded
I have created a registration wizard in ASP.net that uses the MultiView control and I have multiple View Controls within it. An example of one View control can be seen below;
<asp:View ID="address_view" runat="server">
<h1>Address:</h1>
<asp:Button ID="add_new_address" CssClass="blue" runat="server" Text="Add New Address" OnClick="add_new_address_Click" />
<div id="add_address_div" runat="server">
<asp:DropDownList ID="address_dropdown_insert" runat="server">
<asp:ListItem Value="Home">Home Address</asp:ListItem>
<asp:ListItem Value="Term">Term Time Address</asp:ListItem>
<asp:ListItem Value="Mail">Mail Address</asp:ListItem>
<asp:ListItem Value="Business">Business Address</asp:ListItem>
</asp:DropDownList><br />
Address 1:
<asp:TextBox Text="" runat="server" ID="address_1TextBox" /><br />
Address 2:
<asp:TextBox Text="" runat="server" ID="address_2TextBox" /><br />
Town/City:
<asp:TextBox Text="" runat="server" ID="town_cityTextBox" /><br />
County:
<asp:TextBox Text="" runat="server" ID="countyTextBox" /><br />
PostCode:
<asp:TextBox Text="" runat="server" ID="postcodeTextBox" /><br />
Country:
<asp:TextBox Text="" runat="server" ID="countryTextBox" />
<asp:Button runat="server" CommandName="Insert" Text="Insert" ID="InsertButton" OnClick="insert_address_button_Click" />
<asp:Button runat="server" CommandName="Cancel" Text="Clear" ID="Button4" OnClick="cancel_address_button_Click" /><br />
</div>
<asp:ListView ID="address_list" runat="server" DataSourceID="user_address" DataKeyNames="address_id">
<EditItemTemplate>
// code here
</EditItemTemplate>
<EmptyDataTemplate>
<br />
<p>There are currently no addresses found, please click the button above to add a new address.</p>
</EmptyDataTemplate>
<ItemTemplate>
//code here
</ItemTemplate>
<LayoutTemplate>
//code here
</LayoutTemplate>
</asp:ListView>
<br />
<asp:Button CommandName="NextView" ID="Button1" runat="server" Text="Next" />
</asp:View>
The database table that the insert form inserts to is named address. It has the following fields
address_id
user_id
address_type
address_1
address_2
town_city
county
postcode
country
The user_id is pulled from another table called users.
I have the following C# to get the user_id of the current user who is logged in;
//get id of logged in user
string user_id = Session["user_id"].ToString();
My question is, how can I prevent a user from continuing onto the next view when they click Button1 if their user_id does not appear in the address table?
I'm fairly new to C# so any help would be much appreciated.
Presentationally you will want to disable Button1 until an address is entered. Initally your Button1 markup will include Enabled = "false"
<asp:Button CommandName="NextView" Enabled="false" ID="Button1" runat="server" Text="Next" />
Then within the insert_address_button_Click handler, after an address has been successfully added, enable the button like so:
protected void insert_address_button_Click(object sender, EventArgs e)
{
// ..insert the address. If successful, enable the "Next" button
Button1.Enabled = true;
}
That's a simple approach, but should do what you ask.
EDIT:
To address Button1's state in the user returns to the address view:
protected void Page_Load(object sender, EventArgs e)
{
Button1.Enabled = address_list.Items.Any();
}
When using the prebuilt Membership features in ASP.NET (i.e. the Login.aspx, Register.aspx, etc...), I can create custom error messages using the following in my ASP.NET Login page in the asp:Login element (notice the OnLoginError attribute which calls my code-behind method).
<asp:Login ID="LoginBlock" runat="server" ViewStateMode="Disabled" RenderOuterTable="false" OnLoginError="LoginBlock_LoginError">
Is there such an attribute in the prebuilt Register.aspx page? If so, which registration HTML element would it go into? I've been looking on SO and through the Intellisense prompts and I'm not seeing what it would be.
Here is my Registration page from the Content element down:
<asp:Content ID="bodyContent" ContentPlaceHolderID="dashboardBody" runat="server">
<script type="text/javascript" src="../Scripts/dcfpakHelper.js"></script>
<asp:ScriptManager ID="ScriptManager" runat="server" AsyncPostBackTimeout="1200" EnablePageMethods="true" EnablePartialRendering="true" EnableCdn="true" />
<asp:CreateUserWizard runat="server" ID="RegisterUser" ViewStateMode="Disabled" OnCreatedUser="RegisterUser_CreatedUser" OnRegistrationError="">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="wizardStepPlaceholder" />
<asp:PlaceHolder runat="server" ID="navigationPlaceholder" />
</LayoutTemplate>
<WizardSteps>
<asp:CreateUserWizardStep runat="server" ID="RegisterUserWizardStep">
<ContentTemplate>
<p class="validation-summary-errors">
<asp:Literal runat="server" ID="ErrorMessage" />
</p>
<fieldset class="form-signin">
<legend>Registration Form</legend>
<asp:Label ID="Label2" CssClass="sr-only" runat="server" AssociatedControlID="Email">Email address</asp:Label>
<asp:TextBox CssClass="form-control" runat="server" placeholder="Email" ID="Email" TextMode="Email" OnTextChanged="SetUserNameTextToEmailText" />
<div style="padding-top: 10px; padding-bottom: 10px">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="Email"
CssClass="field-validation-error text-center alert alert-danger" ErrorMessage="The email address field is required." />
</div>
<asp:Label ID="Label3" CssClass="sr-only" runat="server" AssociatedControlID="Password">Password</asp:Label>
<asp:TextBox CssClass="form-control" runat="server" placeholder="Password" ID="Password" TextMode="Password" />
<div style="padding-top: 10px; padding-bottom: 10px">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="Password"
CssClass="field-validation-error text-center alert alert-danger" ErrorMessage="The password field is required." />
</div>
<asp:Label ID="Label4" CssClass="sr-only" runat="server" AssociatedControlID="ConfirmPassword">Confirm password</asp:Label>
<asp:TextBox CssClass="form-control" placeholder="Confirm Password" runat="server" ID="ConfirmPassword" TextMode="Password" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="ConfirmPassword"
CssClass="field-validation-error" Display="Dynamic" ErrorMessage="The confirm password field is required." />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword"
CssClass="field-validation-error" Display="Dynamic" ErrorMessage="The password and confirmation password do not match." />
<asp:Label ID="Label1" CssClass="sr-only" runat="server" AssociatedControlID="UserName">User name</asp:Label>
<asp:TextBox CssClass="form-control" placeholder="User Name" runat="server" ID="UserName" style="display: none"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserName"
CssClass="field-validation-error" ErrorMessage="The user name field is required." />
<div style="padding-top: 20px">
<asp:Button ID="Button1" CssClass="btn btn-lg btn-default btn-block" runat="server" CommandName="MoveNext" Text="Register" />
</div>
</fieldset>
</ContentTemplate>
<CustomNavigationTemplate />
</asp:CreateUserWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
</asp:Content>
After some work, I figured it out (ironically, it was an answer written in VB.NET that got me on the right path. See the post on this site here. It's under XiaoYong Dai's answer).
In the CreateUserWizard element, I inserted the OnCreateUserError attribute and gave it a method named RegisterUser_CreateUserError.
<asp:CreateUserWizard runat="server" ID="RegisterUser" ViewStateMode="Disabled" OnCreatedUser="RegisterUser_CreatedUser" OnCreateUserError="RegisterUser_CreateUserError">
In the code behind, I then placed the method RegisterUser_CreateUserError:
protected void RegisterUser_CreateUserError(object sender, CreateUserErrorEventArgs e)
{
//Error message handling here.
}
When I ran this and intentionally created a registration error (i.e. a password that did not fit the config file password requirements), the error event went to this method.
I have a repeater with editable rows on the aspx page. The row has a textbox and a required field validator associated to it. On 'save' button click on that row, the required field valiator fires, It is tied to a validationsummary at the top of the page.
Now I have this panel below the repeater with a text box and a save button. This panel is 'opened' using the jquery show method on the click on a linkbutton at the top of this panel.
The required field validator is not firing for this texbox. I have a different validation summary for this textbox; as I need to trigger the validations on click on its save button only.
So I have the code like this,
<asp:ValidationSummary ID="validationSummary" ValidationGroup="ValidationGroup1" EnableClientScript="true" runat="server" />
<asp:ValidationSummary ID="validationSummary1" ValidationGroup="ValidationGroup2" EnableClientScript="true" runat="server" />
<asp:Repeater ID="Teams" runat="server" OnItemCommand="ItemCommand" OnItemDataBound="ItemDataBound">
<HeaderTemplate>
<table >
<tr>
<th>
<asp:Label ID="lbTeamNameHeader" runat="server" Text="TeamNameHeader"></asp:Label></th>
<th></th> </tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="txtTeamName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "txtTeamName")%>' />
<asp:RequiredFieldValidator ID="reqdFieldValTeamName" ErrorMessage="Field cannot be blank" ValidationGroup="ValidationGroup1" runat="server" Display="None" ControlToValidate="txtTeamName"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regularExprTeamName" ErrorMessage="Invalid input for the team name" ValidationGroup="ValidationGroup1" Display="None" ControlToValidate="txtTeamName" runat="server" ValidationExpression="^[a-zA-Z0-9]+$"></asp:RegularExpressionValidator>
</td>
<td>
<asp:Panel ID="panelSave" runat="server" Visible="false">
<asp:LinkButton ID="linkbuttonSave" runat="server" CommandName="Save" ValidationGroup="ValidationGroup1" Text="SAVE" />
<asp:LinkButton ID="linkbuttonCancel" runat="server" CommandName="Cancel" Text="CANCEL" />
</asp:Panel>
</td>
</tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:Repeater>
<asp:LinkButton ID="linkbuttonAddTeam" runat="server" Text="Add New Team" />
<div id="AddPanelDiv" style="display:none;">
<asp:TextBox ID="txtAddTeam" runat="server" />
<asp:RequiredFieldValidator ID="reqdFieldValAddTeam" ErrorMessage="Field cannot be blank" ValidationGroup="ValidationGroup2" runat="server" Display="None" ControlToValidate="txtAddTeam"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regularExprValAddTeam" ErrorMessage="Invalid format" ValidationGroup="ValidationGroup2" Display="None" ControlToValidate="txtAddTeam" runat="server" ValidationExpression="^[a-zA-Z0-9]+$"></asp:RegularExpressionValidator>
<asp:LinkButton ID="linkbuttonCancel" runat="server" Text="CANCEL"></asp:LinkButton>
<asp:LinkButton ID="linkbuttonSaveNewTeam" runat="server" OnClick="linkbuttonSaveNewTeam_OnClick" Text="SAVE" CausesValidation="true" />
</div>
Why on earth the validators for the bottom panel fire? On click of that save button, it straightaway goes to the page method onclick.
If I remove the validation group and click on the save in the repeater, it fires! But thats not what I want..
You are missing ValidationGroup="ValidationGroup2" on your second button it looks like.
<asp:LinkButton ID="linkbuttonSaveNewTeam" runat="server" OnClick="linkbuttonSaveNewTeam_OnClick"
Text="SAVE" CausesValidation="true" ValidationGroup="ValidationGroup2" />
Is it possible to show the error message of a Regular Expression validator in Asp.net into a message box/ dialog box?
I've tried everything i knew but nothing works for me.
Thanks alot
<form id="form1" runat="server">
<asp:Label ID="lblNameRequired" runat="server" Text="*Name :"></asp:Label>
<asp:TextBox ID="txtNameRequired" runat="server" ValidationGroup="Validation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ControlToValidate="txtNameRequired"
Display="None" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblGenderRequired" runat="server" Text="*Gender :"></asp:Label>
<asp:DropDownList ID="ddlGenderRequired" runat="server" ValidationGroup="Validation">
<asp:ListItem Selected="True" Value="-1">--Select--</asp:ListItem>
<asp:ListItem Value="0">Male</asp:ListItem>
<asp:ListItem Value="1">Female</asp:ListItem>
</asp:DropDownList>
<asp:CompareValidator ID="CompareValidatorGender" runat="server" ControlToValidate="ddlGenderRequired"
Display="None" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
ValueToCompare="-1"></asp:CompareValidator>
<br />
<asp:Label ID="lblValidation" runat="server" Text="Fields marked with * are required"></asp:Label>
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate Input" ValidationGroup="Validation" />
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
ShowSummary="False" ValidationGroup="Validation" />
</form>
use the same ValidationGroup text on all validation controls and add a ValidationSummary with the ValidationGroup and ShowMessageBox="true"