Custom Validation when TextBox has value and CheckBox does not - c#

I have a situauation that I need to check on a button click if the user has entered a value into a textbox, but have not checked a checkbox. They need to be advised that they can not enter a value in the textbox without first checking the checkbox. I know I need to use a CustomValidator Control, but other than that I'm lost. Can anyone help me?

In OnClientClick event you can call a javascript method which will do this validation for you.
This should point you in the right direction.

I think the easiest way to do so will be enabling/disabling the textbox base on whether the checkbox is checked.
However, if you want to do the check on button_click, maybe just do checks on both the checkbox and textbox? And output error message to a label or something?
if(TextBox1.Text.Trim() != "")
if(!CheckBox1.Checked)
label1.Text = "Checkbox needs to be checked";
Or, you can do checks when TextBox1.Text has changed.
private void Textbox1_TextChanged(object sender, EventArgs e)
{
if(!CheckBox1.Checked)
label1.Text = "Checkbox needs to be checked";
}

You can implement this functality using javascript/Jquery.Set the onClientClick property of button as below:
<asp:Button ID="btnSubmit" runat="server" onClientClick="ValidateData();"/>
Below is the jquery code:
function ValidateData()
{
if(!$('#checkboxID').is(':checked') && $.trim($('#textBoxID').val())!='')
{
alert('Please check the checkbox before entering text');
}
}

You can try this...
First you must have a button like this...
<asp:Button ID="btnCheck" runat="server" CssClass="m-btn purple" Text="Check" onclintclick="Validate()"/>
Now we can write the validation script...
<script type="text/javascript" language="javascript">
function Validate() {
if(document.getelementid('checkbox1').checked==true)
{
if(document.getelementid('Textbox1').value=="")
{
//Write your code here..
}
}
else
{
alert('Please check the checkbox..');
}
}
</script>
Please feel free to mark as answer if it satisfies you....

Related

How to get ispostback=true when <a href> object is clicked in c#

I have 2 hrefs like below in asp.net 4.5:
</i>
</i>
where I have some process to do in page_load in c# like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//loading data from db;
}
}
When I click on this a href, the page_load event is triggered and IsPostBack comes as false. Therefore, it is loading the data again and again whenever someone clicks previous or next page hrefs, causing a performance issue. I need to prevent this happening, meaning that I want IsPostBack = true after an href link is clicked. What is the best way to handle this issue?
I have tried to use onclientlick="return false;", it did not work.
I have tried to use asp:button and asp:linkbutton like below, did not work.
<asp:Button ID="btnPrev" runat="server" Text="left" OnClick="RedirectPreviousPage" />
protected void RedirectPreviousPage(object sender, EventArgs e)
{
var prevPage = CurrentPage == 1 ? -1 : CurrentPage - 1;
Response.Redirect("/Admin/" + prevPage);
}
What is the best solution? Any help or advise would be appreciated. I've checked lots of previous topics with related issue, but couldn't find a proper solution for my case. Apologies if I am causing a duplication. Regards.
Edit: also did not work.
<script>
function RedirectPreviousPage()
{
window.location.href = "/Admin/<%= prevPage %>";
}
</script>
</i>
Changing hrefs into "asp:LinkButton" and setting AutoPostBack property to true for those linkbuttons fixed my issue.

how change textbox text after clicking on a button inside a gridview

i have one textbox and one button both on a gridview , when user clicks on button i want to get the textbox text and save to database then clear the text! i used code below it works fine and saves to database but cant clear the textbox why ?
protected void sendcm_Click(object sender, EventArgs e)
{
try
{
Button sendcm = (Button)sender;
GridViewRow gvrow = (GridViewRow)sendcm.NamingContainer;
int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
TextBox tt = (TextBox)activity.Rows[gvrow.RowIndex].FindControl("cmtextbox");
if (tt.Text != "")
{
BusinessLayer.StatusComment_Table ncm = new BusinessLayer.StatusComment_Table();
ncm.Id = Convert.ToInt32(Session["ID"].ToString());
ncm.Statusid = SourceID;
ncm.Statuscommentdate = System.DateTime.Now;
ncm.Statuscommenttext = tt.Text;
ncm.Save();
tt.Text = ""; // its not working !!!!
}
}
protected void Page_Load(object sender, EventArgs e)
{
SessionLable.Text = Session["ID"].ToString();
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
activity.DataSource = BusinessLayer.Activity_Table.GetByProfileData(ID, -1, activity.PageSize);
activity.DataBind();
}
You need to do this at the UI level.
Use jquery.post to call the method that saves the data.
return something back to the $.post callback to tell jquery that the post s complete,
then do something like $('#mytextfield').val('')
assuming that the text box has an ID. I am assuming this is HTML?
you might need to rebind your grid because from the code that you posted it's not clear that where are you re binding your grid.
You need to enable AjaxPostback in your page. After that, in your Page_Load logic, include the code
if(IsPostBack){...}else{...}
So you can handle the construction of UI elements depending on whether this is a fresh new view of the page or a postback (page refreshed due to user clicking the button). UI elements are sent to the browser, after that, there is no way for the server to change it except to refresh the page itself.
The manual (and the one I recommend) way is to do this via jQuery postback. As pointed out in the other answer, you'll need to setup an endpoint for the client browser to connect. After the server has done its job, return the result to the client. Then use jQuery to update the textbox.
i did this to solve my problem !
<asp:TextBox ID="cmtextbox" type="text" clientid="cmtextbox" TextMode="MultiLine" placeholder="نظر دهید..." Rows="1" style="resize:none" class="form-control" runat="server"></asp:TextBox>
<asp:Button ID="sendcm" style="margin-top:2px;" OnClick="sendcm_Click" class="btn btn-success btn-sm pull-left " OnClientClick="ClearTextbox(this)" runat="server" Text="ارسال" />
</script>
<script type="text/javascript">
ClearTextbox = function (that) {
$(that).prevUntil('div.stop', '[ClientID="cmtextbox"]').val('');
}
</script>

Change the value of a textbox in a template field from event outside of GridView

I need to be able to change the value of a TextBox(s) in a GridView template field from a TextChanged event. So the user can enter some text in a TextBox outside of the Gridview and then the TextBox(s) in the GridView gets updated to what the user entered.
This is what I need to do:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
template_text_box1.Text( in template field ) = TextBox1.Text << (TextBox1)( outside of gridview )
}
I have tried FindControl. This needs to happen without using any of the GridView events. I am just stumped. Could someone point me in the right direction? Maybe some JavaScript?
I believe that you would want to define a separate TextBox for the display and do something like the following:
double value1;
private void template textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if textBox1.Text (Double.TryParse(textBox1.Text, out value1))
{
textBox15 = value1.ToString();
}
}
This way you can make your other TextBox outside the grid and be able to call it and set to the value that is inputted.
On the .Aspx page, in the GridView column template TextBox add a CSS class.
<asp:TextBox ID="TextBox1" runat="server" CssClass="box-to-change" Text=""></asp:TextBox>
Also on the .Aspx page add a JavaScript function that uses jQuery:
<script type="text/javascript">
function updateAllTextboxes(value)
{
$('input.box-to-change').val(value);
}
</script>
In the code-behind add the JavaScript function as a client OnChange event (will not require PostBack).
otherTextBox.Attributes["onchange"] = "updateAllTextboxes(this.value)";

Hide/Show form based on Dropdownbox selection

I have looked around and haven't found anything concrete.
Is there any tutorials on how to show/hide a form or textbox based on if a value is selected.
I have something like this Dropdown box with (Add, item1, item2,item3 ect..)
if add is selected show a form to add add with some attributes such as (First Name, last Name ect..) else it will just do an action with the selected item.
<select id="target">
<option value="option1" selected="selected">Add</option>
<option value="option2">Item1</option>
</select>
<input type="text" class="textboxclass" />
<div class="someform">
//content
</div>
Default css display property for someform class is none eg:
.someform{display:none;}
Jquery script
<script>
$('#target').change(function() {
var name = $('#target option:selected'),text(); //Item1
var id = $('#target').val(); // option2
if(id =="option2"){
//your logic for this option
//hide textbox
$('.textboxclass').hide();
$('.someform').show();
}else{
$('.textboxclass').show();
$('.someform').hide();
}
//other if else logic
});
</script>
Not tested since im on laptop without any software installed.
I would wire this up in the client-code. Handle the select's onchange event in JavaScript or jQuery and bind a handler to it. Since "Add" is the only one that will show the form, in your handler check for the value selected and if it's the value for "Add", show the form. If it's any other value, hide the form.
If you want to do this in the server code, just handle the event for the selection changed and set the visibility property of your form that way. Either way should be pretty easy.
Doing this on the client allows you to avoid coding around postbacks while removing responsibility of processing the request from the server.
if you want to do this from server side you will need to set the AutoPostBack propetry of DrowpDown list to true,
and in the SelectedIndexChanged event of DropdownList
try this,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
{
entryForm.Visible = true;
viewForm.Visible = false;
}
else if (DropDownList1.SelectedIndex == 1)
{
entryForm.Visible = false;
viewForm.Visible = true;
}
but this is not a good aproach, i will suggest to follow the answers given above, and do it with JavaScript or JQuery

End user add values to a dropdownlist?

I'm populating a dropdownlist in c# asp.net-MVC from a SQL table using Linq2Sql. I'd like for the user to be able to enter something that isn't in the list into the drop down and have it add to the table. Is this possible?
Sounds like you need to add a radio button labeled "Other". When the user clicks the radio button a text box would appear that allows the user to input a new value that you can save to your DB and display in the drop down.
EDIT:
Quick snippet to enable the control using JavaScript:
<script language="javascript" type="text/javascript">
function radioclicked() {
textObj = document.getElementById('<NAME OF TEXT BOX');
textObj.disabled = false;
}
</script>
You can use a check box instead of a radio button so that the enabled property can be toggled.
To completely hide the text box then you will have to look into jQuery/Ajax.
Why can't we use a lightweight Add-on like www.combodropdown.info for this purpose? You can even consider AutoComplete plugin from jQuery, if your app already references jQuery.
Also a combobox will allow a user to enter a value in addition to picking from a list.
My MVC is not so so, but I assume this still applies as MVC is just model view controller.
What if you throw a drop down on your form visible=true, and a textbox on your form visible =false.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" Visible="False"></asp:TextBox>
Fill your drop down:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> s = Enumerable.Range(1, 10).ToList();
DropDownList1.DataSource = s;
DropDownList1.DataBind();
DropDownList1.Items.Add("Other");
}
}
Add an event to handle if someone selects other. If they do make the textbox visible:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.DropDownList1.SelectedItem.Text)
{
case "Other":
this.TextBox1.Visible=true;
break;
default:
this.TextBox1.Visible=false;
break;
}
}
Now you can enter your value and re-store back to the db.

Categories

Resources