also getting error on TargetElement also does not exist, getting args.event only no TargetElement exist
<SFNumericTextBox TValue="int?" Value="10" CssClass="e-custom" ShowSpinButton="true" Change="OnValueChange" />
#code {
private void OnValueChange(ChangeEventArgs args)
{
if (args.TargetElement == NumericTextBoxTargetElement.SpinUp)
{
}
else if (args.TargetElement == NumericTextBoxTargetElement.SpinDown)
{
}
else
{
}
}
}
You can use the ValueChange event for your requirement. The ValueChange event triggers when the NumericTextBox value is changed.
For your scenario, you can compare the previous value with the current value of the NumericTextBox component and then perform your own logic operations based on the result.
#using Syncfusion.Blazor.Inputs
<div style="margin:130px auto;width:300px">
<SfNumericTextBox TValue="int?" Value="10" CssClass="e-custom" ShowSpinButton="true">
<NumericTextBoxEvents TValue="int?" ValueChange="OnValueChange"></NumericTextBoxEvents>
</SfNumericTextBox>
</div>
#code
{
private void OnValueChange(ChangeEventArgs<int?> args)
{
var TempVlaue = args.PreviousValue;
bool result = args.Value > args.PreviousValue ? true : false;
if (result)
{
// Do something if spin up button clicked
}
else
{
// Do something if spin down button clicked
}
}
}
Numeric Textbox ValueChange: https://blazor.syncfusion.com/documentation/numeric-textbox/events#valuechange
List of Native events supported by Numeric Textbox: https://blazor.syncfusion.com/documentation/numeric-textbox/native-events#list-of-native-events-supported
Also, you can refer to the below sample for more information:
https://www.syncfusion.com/downloads/support/directtrac/general/ze/NumericTextBox1682455549
Related
I have a razor component with the following input. I currently use the "GetCourses" method to retrieve a list of courses, and everything works as expected upon button click. I would like to, however, be able to type in some string into the searchbox, and upon hitting the "enter" key, call the same "GetCourses" method. I have duplicated the "GetCourses" method and modified it to work with the #OnKeyDown event, but it does not work. In the debugger, the #OnKeyDown event is triggered with each key press, but it never binds a value to "this.inputValue." I want to capture all of the string characters in the searchbox, not one at a time, and why is it not binding?
<div>
<input type="text"
class="searchbox"
name="user"
placeholder="Search by course name or course ID"
#bind="#this.inputValue"
#onkeydown="#GetCoursesbyKey" />
</div>
<span>
<button class="searchbtn"
#onclick="#(T => GetCourses(inputValue))">
Search
</button>
</span>
#code {
public string inputValue { get; set; }
private async Task GetCoursesbyKey(KeyboardEventArgs? e)
{
var search = this.inputValue;
if (e.Code == "Enter" || e.Code == "NumpadEnter")
{
if (search != null)
{
//perform some logic
}
else
{
//perform some logic
}
//wait on some methods here
}
}
private async Task GetCourses(string search)
{
var search = this.inputValue;
if (search != null)
{
//perform some logic
}
else
{
//perform some logic
}
//wait on some methods here
}
}
Making this small change made the feature work perfectly. I do not have the technical analysis as to why, other than these functions accomplish what I was attempting to do.
<div>
<input type="text"
class="searchbox"
name="user"
placeholder="Search by course name or course ID"
#bind-value="#this.inputValue"
#bind-value:event="oninput"
#onkeydown="#GetCoursesbyKey" />
</div>
I am creating an "export to excel" windows form in c#.
The class contains a CheckedListBox and a "check all" button.
When clicking on the button I want to check all the items in the list in case that at least one checkbox is not checked or uncheck all the checkboxes in case they are all already checked.
I added a small complication, the list of the items is a list of custom objects (see private class inside): "ObjectToExport" class.
public partial class ExcelCustomExportForm : Form
{
private class ObjectToExport
{
private readonly IExcelExportable _form;
public ObjectToExport(IExcelExportable form)
{
_form = form;
}
public override string ToString()
{
return $"{_form.FormName} ({_form.CreatedDate.ToShortDateString()} {_form.CreatedDate.ToShortTimeString()})";
}
}
// each form in the list contains a gridview which will be exported to excel
public ExcelCustomExportForm(List<IExcelExportable> forms)
{
InitializeComponent();
Init(forms);
}
private void Init(List<IExcelExportable> forms)
{
foreach (IExcelExportable form in forms)
{
// Checked List Box creation
FormsCheckedListBox.Items.Add(new ObjectToExport(form));
}
}
private void CheckAllButton_Click(object sender, EventArgs e)
{
// checking if all the items in the list are checked
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
CheckItems(!isAllChecked);
}
private void CheckItems(bool checkAll)
{
if (checkAll)
{
CheckAllButton.Text = "Uncheck All";
}
else
{
CheckAllButton.Text = "Check All";
}
FormsCheckedListBox.CheckedItems.OfType<CheckBox>().ToList().ForEach(c => c.Checked = checkAll);
}
}
The problem is that the following line returns true even if not check box is checked:
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
Similar issue with the following line, if checkAll is true, no check box is checked:
FormsCheckedListBox.CheckedItems.OfType<CheckBox>().ToList().ForEach(c => c.Checked = checkAll);
What is the correct way to fix those two lines of code?
Your Problem begins here.
FormsCheckedListBox.Items.Add(new ObjectToExport(form));
and
var isAllChecked = FormsCheckedListBox.Items.OfType<CheckBox>().All(c => c.Checked);
You are adding instances of 'ObjectToExport' to the FormsCheckedListBox, but while filtering, you are checking filtering with CheckBox.
This means, your filtered query always return empty, and query never reaches All. This can be demonstrated with following example.
var list = new [] { 1,2,3,4};
var result = list.OfType<string>().All(x=> {Console.WriteLine("Inside All"); return false;});
The result of above would be True, and it would never print the "Inside All" text. This is what is happening with your queries.
You can find if any of the checkbox is checked using
var ifAnyChecked = checkedListBox1.CheckedItems.Count !=0;
To change state, you could do the following.
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
// Do something
}
}
I have a form with two textboxes. I am retrieving data from the
database to populate the boxes. When my user clicks on submit button
and the content of the 2 textboxes does not change, I dont want to go through
the code.
How do I determine when the content of the boxes changes and when it does not change?
Do I need to make some kind of comparison to what I have in memory?
public ActionResult Edit(profile objprofiler)
{
if (ModelState.IsValid)
{
//Go fetch the existing profile from the database
var currentProfile = db.Profiles.FirstOrDefault(p => p.ProfileId == objprofiler.ProfileId);
//Update the database record with the values from your model
currentProfile.City = objprofiler.City;
currentProfile.State = objprofiler.State;
//Commit to the database!
db.SaveChanges();
ViewBag.success = "Your changes have been saved";
return View(profiler);
}
}
You can compare the values with a simple if condition. Something like this:
if ((currentProfile.City != objprofiler.City) || (currentProfile.State != objprofiler.State))
{
currentProfile.City = objprofiler.City;
currentProfile.State = objprofiler.State;
db.SaveChanges();
}
Or use whatever logic you're trying to achieve, really. Whether you want to compare for each field individually, use a && instead of an ||, etc. The logic you want to implement is up to you. But you'd perform the comparison in an if statement.
Note also that you can use string.Equals() instead of just the == operator to compare strings with some more options, such as case sensitivity options and other useful things.
If the comparison gets more complex, you might also encapsulate it in the profile object itself. Perhaps by overriding .Equals(), though that has other implications when testing for equality. Maybe just a simple helper function:
public bool IsEqualTo(profile obj)
{
return this.City == obj.City
&& this.State == obj.State;
}
Then in the controller you can just use that method:
if (!currentProfile.IsEqualTo(objprofiler))
db.SaveChanges();
The way I typically handle this is by setting a 'dirty' flag any time a data change event occurs on any of the form's controls.
When the user comes to submit the form, I just check the state of the flag to see whether any changes need to be saved. This avoids having to compare all data to their previous states, which can be a nuisance if there are a lot of input controls on the form.
For example:
bool isDirty;
private void textBox_TextChanged(object sender, EventArgs e)
{
// Possible validation here
SetDirty(true);
}
private void SetDirty(bool dirty)
{
// Possible global validation here
isDirty = dirty;
}
private void Submit()
{
if(isDirty)
{
// Save logic
}
}
This approach allows you to run any global validation logic whenever any data is changed.
Caveat: If a user makes a change then reverts it, the form will still submit the data.
On the client side you can check if the value has changed by running some js to compare the elements value to its initial value. Something like this.
function hasFormChanged() {
//textboxes, textareas
var els = document.querySelectorAll('input[type="text"], textarea, input[type="number"]');
for (i = 0; i < els.length; i++) {
var el = els[i];
if (el.value !== el.defaultValue) {
return true;
}
}
//checkboxes and radios
els = document.querySelectorAll('input[type="radio"], input[type="checkbox"]');
for (i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked !== el.defaultChecked) {
return true;
}
}
//select
els = document.querySelectorAll('select');
for (i = 0; i < els.length; i++) {
var el = els[i];
if (el.options[el.selectedIndex].value != '') {
if (!el.options[el.selectedIndex].defaultSelected) {
return true;
}
}
}
//if we get here then nothing must have changed
return false;
}
and it that function return true indicating that something has changed you can set a hidden form value like this
<input type="hidden" value="false" id="AnyUpdates" name="AnyUpdates"/>
to true.
Then in your controller update read that field to determine if you need to do your db stuff.
I am not able to read the Checked status of my custom checkbox control.
I created this control so that it would rendor correctly for easy use with bootstrap.
The control renders perfectly, and I have all the function that I want/need EXCEPT being able to read the checked status of the input when the user clicks 'submit'.
Custom Server Control Code (C#):
public class InlineBootstrapCheckBox : CheckBox, IPostBackDataHandler, ICheckBoxControl
{
private string value;
private string labelCSS;
private string labelID;
public string LabelID
{
get
{
if (!string.IsNullOrEmpty(this.labelID))
{
return this.labelID;
}
else
{
return null;
}
}
set
{
this.labelID = value;
}
}
public string LabelCSS
{
get
{
if (!string.IsNullOrEmpty(this.labelCSS))
{
return this.labelCSS;
}
else
{
return null;
}
}
set
{
this.labelCSS = value;
}
}
public string Value
{
get
{
if (!string.IsNullOrEmpty(this.value))
{
return this.value;
}
else
{
throw new NotImplementedException("You must set a 'Value' for InlineBootstrapCheckBox Controls");
}
}
set
{
this.value = value;
}
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.WriteLine(string.Format("<label id=\"{0}\" class=\"{1}\" for=\"{2}\">", (this.LabelID != null) ? this.LabelID : string.Concat(this.ID, "_Label"), (this.LabelCSS != null) ? string.Concat(this.LabelCSS, " checkbox-inline") : "checkbox-inline", this.ID));
writer.WriteLine(string.Format("<input type=\"checkbox\" id=\"{0}\" value=\"{1}\">", this.ID, this.Value));
writer.WriteLine(this.Text);
writer.WriteLine("</label>");
}
}
Markup Code (.ASPX):
<div class="form-group">
<label id="lblCategories" class="col-sm-3 control-label">Categories</label>
<div class="col-sm-9">
<cookout:InlineBootstrapCheckBox runat="server" ID="chkRibs" Text="Ribs" Value="1" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkChicken" Text="Chicken" Value="2" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkBrisket" Text="Beef Brisket" Value="3" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkPork" Text="Pork" Value="4" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkAnythingBut" Text="Anything But" Value="5" />
</div>
</div>
Code Behind (C#):
This is where I think my problem is?
protected void btnSubmit_Click(object sender, EventArgs e)
{
ProRegistration regInfo = new ProRegistration();
regInfo.TeamName = this.txtTeamName.Text.ToString();
regInfo.ContactName = this.txtContactName.Text.ToString();
regInfo.StreetAddress = this.txtContactAddress.Text.ToString();
regInfo.City = this.txtContactCity.Text.ToString();
regInfo.State = this.txtContactState.Text.ToString();
regInfo.ZipCode = this.txtContactZip.Text.ToString();
regInfo.Email = this.txtContactEmail.Text.ToString();
regInfo.Phone = this.txtContactPhone.Text.ToString();
regInfo.IsRibs = this.chkRibs.Checked;
regInfo.IsChicken = this.chkChicken.Checked;
regInfo.IsBrisket = this.chkBrisket.Checked;
regInfo.IsPork = this.chkPork.Checked;
regInfo.IsAnythingBut = this.chkAnythingBut.Checked;
regInfo.Created = DateTime.Now;
DataManager.InsertProfessionalRegistration(regInfo);
}
...So basically what I need is to be able to get a positive response when I try to submit this object to my database. Currently, no matter the click status, I get a false result.
I have been trying to research an answer to this for about 3 hours now to no avail.
Thank you!
I don't know bootstrap but it looks like you are injecting an html checkbox into the output. If this is the case it will not be recognized as a server control on postback, however you can get its value by using the request.form object.
string result=Request.Form["thecheckboxid"];
I have a custom validator on a page:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ControlToValidate="ddlProposer" ErrorMessage="Please select some values."
Display="Dynamic" onservervalidate="CustomValidator2_ServerValidate"
ClientValidationFunction="CustomValidator2_ClientValidate">
</asp:CustomValidator>
It must be valid, when a server-side list is not empty (or: the ListCount variable > 0). This list may change after the page has been loaded (via buttons on update panel):
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
...
There is no problem with server-side validation:
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = this.ProposersList.Count > 0;
}
The problem is with client-side part. I've been trying something like this:
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var serverVariable = <%= ListCount %>;
alert(serverVariable);
arguments.IsValid = serverVariable > 0;
}
</script>
however, it fires only on first page load, and the ListCount variable is always 0 (so does the serverVariable).
The question is: is there an easy-way to make it working? So the Javascript gets the current value of some server-side variable?
you can use hidden variable on the page level and by setting its value from server side and validate on client side.
<input type="hidden" id="ListCount" runat="server" value="0" />
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
ListCount=value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var count= document.getElementById("ListCount").value;
alert(count);
arguments.IsValid = count > 0;
}
You'll have to do it in plain javascript, and there is no sens of getting the server side variable since it won't be up to date at the moment client validation will be done.
What you need is pass your ddl html element to your CustomValidator2_ClientValidate function and check if it contains option html elements, that should do the trick.