Create Asp.net Reset Button - asp.net

Is there any ways to create reset button to clear all text in text fields in asp form? When user hits the reset button, all text entered by them will clear and they are enable to enter back text in the area.

As per my knowledge there is no such reset functionality provided by Asp.Net.
We can achieve the reset like this
btnReset.Attributes.Add("onClick", "document.forms[0].reset();return false;");
Or
Like this
<input type='button' id='resetButton' value='Reset' onclick='theForm.reset();return false;'/>
Or OnClientclick of asp.net button use this theForm.reset();return false;

try this create a button with reset and in click event write ClearInputs(Page.Controls); and event will call this method.
protected void Button2_Click(object sender, EventArgs e)
{
ClearInputs(Page.Controls);
}
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}

In the button click method, set all textbox.text.length values to 0. either do it one by one, which is the simple way, or do it by getting all controls of type textbox on the page, which is tad bit more sophisticated, but could be much less typing, depending on the number of textboxes. Definitely more maintainable.
private void ChangeBtn_Click(object sender, EventArgs e)
{
foreach(Control c in Page.Controls)
{
if (c.Controls.Count > 0)
{
foreach(Control c2 in c.Controls)
{
if (c2.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
myspan.InnerHtml = ((TextBox)c2).Text;
((TextBox)c2).Text = ""; //or ((TextBox)c2).Text.Length = 0;
}
}
}
}
}
http://msdn.microsoft.com/en-us/library/20zys56y(v=vs.90).aspx

Create a Click event to the Button control and use the following codes below:
foreach (Control control in Page.Controls)
{
if (control is TextBox)
{
TextBox txt = (TextBox)control;
txt.Text = "";
}
}
This will save you some time to clear all the textboxes inside the web form.

Use Jquery the easiest way to find any type of control and will not have post back event.
$('input[type=text], textarea')
Use foreach loop for clearing value.

Please note that
btnReset.Attributes.Add("onClick", "document.forms[0].reset();return false;");
will not work in clearing pages that are posted back, i.e. If a text box had a value "Silly me" and has been posted back, this code will reset to the post back value which is "Silly me".
The workaround is to repost the page with cleared values - try the following code (it worked for me)
OnClientClick="document.location.href=document.location.href;"
will reload the page with cleared values...

I have multiple type of inputs in my page (TextBox, DropDownList and CheckBox), so here is how I reset them all
Put an <asp:Panel> that wraps my inputs
Run BtnClear_Click on Clear button click
Loop each inputs and reset text/selection/checked value by types
The codes
Default.aspx
<asp:Panel ID="PanelReport" runat="server">
...
<asp:TextBox ID="fldSpeedoMula" runat="server"></asp:TextBox>
<asp:DropDownList ID="ddlPlateNo" runat="server" CssClass="form-control"></asp:DropDownList>
<asp:CheckBox ID="cbCard" runat="server" />
<asp:CheckBox ID="cbCash" runat="server" />
<asp:Button ID="BtnClear" runat="server" Text="Clear" CssClass="button" OnClick="BtnClear_Click"/>
...
</asp:Panel>
Default.aspx.cs
protected void BtnClear_Click(object sender, EventArgs e)
{
// Clear all inputs
foreach (DropDownList ddl in PanelReport.Controls.OfType<DropDownList>())
{
ddl.SelectedIndex = 0;
}
foreach (TextBox fld in PanelReport.Controls.OfType<TextBox>())
{
fld.Text = string.Empty;
}
foreach (CheckBox cb in PanelReport.Controls.OfType<CheckBox>())
{
cb.Checked = false;
}
}

Related

how to store a label control text into a textbox control value

i am trying to set the value of a textbox control in my aspx page as the value of a label text. I am using the following code but nothing happens. I have tried from the code behind file using c# and then I want to assign the textbox value to a session variable. If I just assign a string value like "Hello"it works, but otherwise nothing works.
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
//Response.Redirect("booknow.aspx");
}
}
I also tried with Javascript, but no use:
var mtcid = parsedData.employeeCode;
document.getElementById('txtmtcid').value = mtcid;
The above js code works fine if I am assigning the value of mtcid to a label text, but not for the text box. please help.
You don't show things that could be messing this up.
and we can't see your markup used.
What does your page load event look like. Keep in mind that EVERY button click, post-back or ANY control on the page with a event code stub WILL RUN the page load event EVERY time. the page load event runs every time, and BEFORE your button click code runs.
So, if I have this markup:
<asp:Label ID="blbtest" runat="server" Text="zoo"></asp:Label>
<br />
<asp:TextBox ID="txtmtcid" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<br />
And then code behind of this:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
}
I then get this when I click on the button
So, we can see how the lable text is now copy to the text box.
You have to post more markup, and give futher detilas (such as some grid view, repeater or any other boatload of features that well explain your issue).
Note that you can double click on the button in the web forms designer to create a event click for the button. Its possible that no event code for the button exists, and your button click code and code behind never runs.
So this is the markup:
<asp:Label ID="blbtest" runat="server" ClientIDMode="Static">
</asp:Label>
<asp:Button ID="btnBook" runat="server" Text="Book Now"
CssClass="spaces-info__button" OnClick="btnBook_Click"/>
<asp:TextBox ID="txtmtcid" runat="server">
</asp:TextBox>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!(Session["username"] == null))
{
string usn = Session["username"].ToString();
lblusn.Text = usn;
}
}
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
Response.Redirect("booknow.aspx");
}
updated js:
$(function () {
//dom is ready
var request = new XMLHttpRequest;
var usn = document.getElementById('lblusn').innerHTML;
//var usn = "juhaina.ahmed";
console.log(usn);
request.open('GET', "URL" + usn + ""); //of course I have replaced
the URL here
request.onload = function () {
var response = request.response;
var parsedData = JSON.parse(response);
console.log(parsedData);
var nm = parsedData.fullName;
document.getElementById('lblfullnm').innerHTML = nm;
var mtcid = parsedData.employeeCode;
document.getElementById('blbtest').innerHTML = mtcid;
document.getElementById('txtmtcid').value =
document.getElementById('blbtest').innerHTML
};
request.send();
});
I am new to js, and asp.net, so trying to browse whatever possible and work things out here. The session variable value is just not getting passed to next page. Honestly, i dont need the textbox, I dont know if label text can be stored in session variables. If thats possible, then all I want to do is assign the blbtest label text to the session variable, but that also didnt work,but if I am hard coding it like:
Session["mtcid"]="D-11234"
this works and the value of session variable is passed.
hence I am trying now with textbox. Please let me know if theres a better approach to this.
If there is a way to avoid the use of the label and textbox and simply pass the session variable, Session["username"] from the code behind to the javascript, that would be great. how can I do it?

Setting Button Properties in ListView ItemTemplate

I have a ListView which displays event bookings. If there is a time slot available, I want to make a booking button visible beside that data item. I have tried doing this in both the OnItemCreated and OnItemDataBound event handlers to no avail.
In this particular scenario, there are four results and all are available. However, the button only appears beside the last result. It's like something is being overwritten. I tried setting the ID property to something different in each round of the loop but that failed at runtime.
I also tried flipping the logic by setting the visibility of the button to false in the markup initially - three buttons would appear and no button beside the last data item.
I originally tried storing the Button control in ViewState and got the "not serializable" error. So I switched to storing the object in Session state.
Can someone point me in the right direction?
<ItemTemplate>
...
<asp:Button ID="reserveButton" Text="Book Now" Visible="false"
OnClick="ReserveButton_Click" runat="server" />
</ItemTemplate>
// After the DataBind() method in the search button handler
...
int rowCount = resultsDS.Tables[0].Rows.Count;
for (int i = 0; i < rowCount; i++)
{
if (resultsDS.Tables[0].Rows[i]["Available"].ToString().Contains("Available Time Slots"))
{
reserveButton = Session["ReserveButton"] as Button;
reserveButton.Visible = true;
}
}
...
protected void ResultsList_ItemCreated(object sender, ListViewItemEventArgs e)
{
if (e.Item is ListViewItem)
{
reserveButton = e.Item.FindControl("reserveButton") as Button;
Session["ReserveButton"] = reserveButton;
}
}
For the benefit of others, I was able to solve this as follows:
protected void ResultsList_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item is ListViewItem)
{
DataRowView row = (DataRowView)e.Item.DataItem;
if (row["Available"].ToString().Contains("Available Time Slots"))
{
Button reserveButton = e.Item.FindControl("reserveButton") as Button;
reserveButton.Visible = true;
}
}
}

radio button list in repeater control

I have a repeater control in my page. I need to have a radio button in all the rows(Item template) on checking an radio button the remaining radio buttons must unchecked.
How to do this?
Thanks in advance,
Tor
Unfortunately, it's a known bug ( http://support.microsoft.com/kb/316495 ) that the GroupName property doesn't work as expected when used in a Repeater. The problem is that the Repeater implements the INamingContainer interface which requires all nested controls to have a unique name when rendered out to HTML. This causes the radio buttons to break because in order for them to work properly they must have identical names.
There are 2 work-arounds that I've come across:
1 - The first is a client-side javascript solution. It was provided by Microsoft support. Or an easier to read version here.
The instructions are as follows. Include the following javascript in the HEAD:
function SetUniqueRadioButton(nameregex, current)
{
re = new RegExp(nameregex);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i]
if (elm.type == 'radio')
{
if (re.test(elm.name))
{
elm.checked = false;
}
}
}
current.checked = true;
}
Now the function needs to be linked to the Radio Buttons in the OnDataItemBound event of the repeater. Replace "RadioButton" with the name of your RadioButton control and "RadioGroup" with the GroupName you have chosen:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
RadioButton rb = (RadioButton) e.Item.FindControl("RadioButton");
string script = "SetUniqueRadioButton('Repeater1.*RadioGroup',this)";
rb.Attributes.Add("onclick", script);
}
2 - The second solution is a server-side solution using a custom usercontrol that inherits from RadioButton. The tutorial and source code can be downloaded here: http://www.codeproject.com/KB/webforms/How_group_RButtons.aspx
Just add a OnCheckedChanged event to the radio button, loop all the radiobuttons in the repeater to uncheck them. You can use UpatePanel if you do not want postback.
.aspx
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_OnCheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:Repeater>
.cs
protected void RadioButton1_OnCheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
RadioButton rbtn = (RadioButton)item.FindControl("RadioButton1");
rbtn.Checked = false;
}
((RadioButton)sender).Checked = true;
}
I know this is old, but the reason for the buttons not working is because the name attribute is being overwritten. If using jQuery, you could assign the radio button to a class then set the name attribute to override the new name.
$('.MyRadioClass').attr("name","MyFixedName");
Another simpler alternative, where no fancy formatting is required, is to use a RadioButtonList:
<asp:RadioButtonList ... />

Calendar, Dynamic LinkButton CommandEventHandler Help

I am attempting to create a calendar which is just a simple UI to display dates and dates to users of our system. I have overridden the Calendar's "DayRender" event to gain access to each cell and then insert a couple of dynamic controls to display specific data. The display of the controls works great. However, I recently wanted to add a LinkButton with command arguments and capture the event to run some other logic and change the UI. I have gotten the LinkButton to display properly and it renders as a simple "" tag with the ID that is assigned. However clicking on the link does nothing and it appears that the normal "href='...javascript action...'" portion of the link is not being generated. I have a feeling this is all due to the fact that I am adding the control at the Day Render stage in the page life cycle. But if that was the case the control probably would not show up at all.
Any ideas as to why the click action is not being added yet the text and everything else are? Code is below.
Thanks for your time
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (Schedule != null)
{
var dayReq = from day in Schedule
where day.RequiredDate == e.Day.Date
where day.RequiredQty != 0
select day;
if (dayReq.FirstOrDefault() != null)
{
//Open the Date
e.Cell.Controls.Add(new LiteralControl("<br /><div class=\"auth-sched-req\">Req Qty: <strong>" + String.Format("{0:#,#.###}", dayReq.FirstOrDefault().RequiredQty) + "</strong><br />Prom Date: "));
//Create a link button for the promise date
LinkButton lb = new LinkButton();
lb.ID = dayReq.FirstOrDefault().ItemId.ToString();
lb.Text = dayReq.FirstOrDefault().RequiredDate.ToShortDateString();
lb.CommandName = "ShowPromise";
lb.CommandArgument = dayReq.FirstOrDefault().ItemId.ToString();
lb.Command +=new CommandEventHandler(lb_Command);
e.Cell.Controls.Add(lb);
//Close the Date
e.Cell.Controls.Add(new LiteralControl("</div>"));
}
}
}
protected void lb_Command(Object sender, CommandEventArgs e)
{
//Do some magic here
Response.Write(e.CommandArgument.ToString());
}
try this
<script type="text/javascript">
function calendarClick(day) {
document.getElementById('<%= hfValue.ClientID %>').value = day;
document.getElementById('<%= ghostButton.ClientID %>').click();
}
</script>
<asp:Button ID="ghostButton" runat="server" Style="display: none" OnClick="ghostButton_Click" />
<asp:HiddenField ID="hfValue" runat="server" />
code behind:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
// ...
e.Cell.Attributes["onclick"] = string.Format("calendarClick({0})", dayReq.FirstOrDefault().ItemId.ToString());
// ...
}
protected void ghostButton_Click(object sender, EventArgs e1)
{
string value = hfValue.Value;
// ...
}
Check if AutoEventWireup is set to true i.e.
AutoEventWireup="true"
I ended up going another route with this request. None of the proposed solutions worked and I never could get it to work. One option we looked at was creating a custom table to build the control. We ended up changing where the information was changed and just used the calendar control as the display mechanism.
Sorry for the delay!

How to programmatically create and use a list of checkboxes from ASP.NET?

I have a page with a table of stuff and I need to allow the user to select rows to process. I've figured out how to add a column of check boxes to the table but I can't seem to figure out how to test if they are checked when the form is submitted. If they were static elements, I'd be able to just check do this.theCheckBox but they are programaticly generated.
Also I'm not very happy with how I'm attaching my data to them (by stuffing it in there ID property).
I'm not sure if it's relevant but I'm looking at a bit of a catch-22 as I need to known which of the checkboxes that were created last time around were checked before I can re-run the code that created them.
Edit:
I've found an almost solution. By setting the AutoPostBack property and the CheckedChanged event:
checkbox.AutoPostBack = false;
checkbox.CheckedChanged += new EventHandler(checkbox_CheckedChanged);
I can get code to be called on a post back for any check box that has changed. However this has two problems:
The call back is processed after (or during, I'm not sure) Page_Load where I need to use this information
The call back is not called for check boxes that were checked when the page loaded and still are.
Edit 2:
What I ended up doing was tagging all my ID's with a know prefix and stuffing this at the top of Form_Load:
foreach (string v in this.Request.Form.AllKeys)
{
if (v.StartsWith(Prefix))
{
var data = v.Substring(Prefix.Length);
}
}
everything else seems to run to late.
I'm going to assume you're using a DataList but this should work with and Control that can be templated. I'm also going to assume you're using DataBinding.
Code Front:
<asp:DataList ID="List" OnItemDataBound="List_ItemDataBound" runat="server">
<ItemTemplate>
<asp:CheckBox ID="DeleteMe" runat="server"/>
<a href="<%# DataBinder.Eval(Container, "DataItem.Url")%>" target="_blank">
<%# DataBinder.Eval(Container, "DataItem.Title")%></a>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="DeleteListItem" runat="server" OnClick="DeleteListItem_Click" ></asp:Button>
Code Behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadList();
}
protected void DeleteListItem_Click(object sender, EventArgs e)
{
foreach (DataListItem li in List.Items)
{
CheckBox delMe = (CheckBox)li.FindControl("DeleteMe");
if (delMe != null && delMe.Checked)
//Do Something
}
}
LoadList();
}
protected void LoadList()
{
DataTable dt = //Something...
List.DataSource = dt;
List.DataBind();
}
protected void List_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
string id = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
CheckBox delMe = (CheckBox)e.Item.FindControl("DeleteMe");
if (delMe != null)
delMe.Attributes.Add("value", id);
}
}
}
First, make sure that each Checkbox has an ID and that it's got the 'runat="server"' in the tag.
then use the FindControl() function to find it.
For example, if you're looping through all rows in a GridView..
foreach(GridViewRow r in Gridview1.Rows)
{
object cb = r.FindControl("MyCheckBoxId");
if(r != null)
{
CheckBox chk = (CheckBox)cb;
bool IsChecked = chk.Checked;
}
}
Postback data is restored between the InitComplete event and the PreLoad event. If your checkboxes are not created until later then the checkboxes will play "catch up" with their events and the data will be loaded into the control shortly after it is created.
If this is to late for you then you will have to do something like what you are already doing. That is you will have to access the post data before it is given to the control.
If you can save the UniqueId of each CheckBox that you create then can directly access the post data without having to given them a special prefix. You could do this by creating a list of strings which you save the ids in as you generate them and then saving them in the view state. Of course that requires the view state to be enabled and takes up more space in the viewstate.
foreach (string uniqueId in UniqueIds)
{
bool data = Convert.ToBoolean(Request.Form[uniqueId]);
//...
}
Your post is a little vague. It would help to see how you're adding controls to the table. Is it an ASP:Table or a regular HTML table (presumably with a runat="server" attribute since you've successfully added items to it)?
If you intend to let the user make a bunch of selections, then hit a "Submit" button, whereupon you'll process each row based on which row is checked, then you should not be handling the CheckChanged event. Otherwise, as you've noticed, you'll be causing a postback each time and it won't process any of the other checkboxes. So when you create the CheckBox do not set the eventhandler so it doesn't cause a postback.
In your submit button's eventhandler you would loop through each table row, cell, then determine whether the cell's children control contained a checkbox.
I would suggest not using a table. From what you're describing perhaps a GridView or DataList is a better option.
EDIT: here's a simple example to demonstrate. You should be able to get this working in a new project to test out.
Markup
<form id="form1" runat="server">
<div>
<table id="tbl" runat="server"></table>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</div>
</form>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
var row = new HtmlTableRow();
var cell = new HtmlTableCell();
cell.InnerText = "Row: " + i.ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
CheckBox chk = new CheckBox() { ID = "chk" + i.ToString() };
cell.Controls.Add(chk);
row.Cells.Add(cell);
tbl.Rows.Add(row);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (HtmlTableRow row in tbl.Rows)
{
foreach (HtmlTableCell cell in row.Cells)
{
foreach (Control c in cell.Controls)
{
if (c is CheckBox)
{
// do your processing here
CheckBox chk = c as CheckBox;
if (chk.Checked)
{
Response.Write(chk.ID + " was checked <br />");
}
}
}
}
}
}
What about using the CheckBoxList control? I have no Visual Studio open now, but as far as I remember it is a DataBound control, providing DataSource and DataBind() where you can provide a list at runtime. When the page does a postback you can traverse the list by calling something like myCheckBoxList.Items and check whether the current item is selected by calling ListItem.Selected method. This should work.
Add them in an override of the CreateChildControls method of the Page. Be sure to give them an ID! This way they get added to the control tree at the correct time.
IMHO The best way would be to use DataBound Templated Control though, i.e. something like a ListView (in .NET 3.5). then in pageload after postback traverse all items in the databound control and use item.FindControl to get at the actual checkbox.
What I ended up doing was tagging all my ID's with a know prefix and stuffing this at the top of Form_Load:
foreach (string v in this.Request.Form.AllKeys)
{
if (v.StartsWith(Prefix))
{
var data = v.Substring(Prefix.Length);
}
}
everything else seems to run to late.

Resources