The current form is here. It is not complete, and only a couple options will work.
Select "Image CD" and then any resolution and click "Add to Order." The order will be recorded on the server-side, but on the client-side I need to reset the product drop-down to "{select}" so that the user will know that they need to select another product. This is consistant with the idea that the sub-selections disappear.
I don't know whether I should be using ASP postback or standard form submittal, and most of the fields need to be reset when the user adds an item to the order.
I'd use Response.Redirect(Request.RawUrl) method to reset the form data from the server side.
A little explanation: this is PRG design pattern
Used to help avoid certain duplicate
form submissions and allow user agents
to behave more intuitively with
bookmarks and the refresh button.
A workaround for this question:
necessary data may be stored in Session for example. This means we getting the data with the first POST, putting it to the storage, performing redirect and getting it back.
In the pageload event on the form, you need to add something simalar to this:
if (IsPostBack)
{
//Proccess the order here
ProductOption.SelectedIndex = 0;
}
That will allow you to process the order, but then start over the order form.
The simplest means would be a recursive function that forks on the type of control
private void ResetControls( Control control )
{
if ( control == null)
return;
var textbox = control As TextBox;
if ( textbox != null )
textbox.Text = string.Empty;
var dropdownlist = control as DropDownList;
if ( dropdownlist != null )
dropdownlist.SelectedIndex = 0; // or -1
...
foreach( var childControl in controlControls )
ResetControls( childControl );
}
You would this call this function in your Load event by passing this. (This is presuming you want to reset more than a single control or small list of controls).
Related
I want to create dynamic text boxes during run time.
Suppose im gettng a text from a database as "# is the capital of India" now i want to replace that "#" by text box while it is rendered to user as below
<asp:TextBox runat="server" id = "someid"></asp:TextBox> is the capital of India
Im able to get the textbox and text as combination. However I cannot access the textboxes with the given id and when any event occurs on the page the textboxes are lost as they logically does not exist untill their state is stored.
I also went through the concepts of place holder and Viewstate to store the dynamically created controls and make their id's available for the methods, but as far as I tried I could not meet the textbox and text combination requirement.
Im looping over the entire text recieved from database and checking if there is any"#". Is yes then i want to replace it with a textbox on which i can call methods to take back the value entered in the text box to database and store it.
eg: text is "#" is the capital of India
for (int i = 0; i < que.Length; j++) //que holds the text
{
if (que[i] == '#')
{
//Textbox should be created
}
else
{
//the texts should be appended before or after the textbox/textboxes as text demands
}
}
On button click I'm passing request to database, which will send me necessary details i.e. question text, options and also saves the current checked value etc.
protected void BtnLast_Click(object sender, EventArgs e)
{
CheckBox1.Checked = false;
CheckBox2.Checked = false;
CheckBox3.Checked = false;
CheckBox4.Checked = false;
QuestionSet q = new QuestionSet();
StudentB b = new StudentB();
q = b.GetQuestion(1, 1, qid, 'L', 0, Checked, date);
qid = Convert.ToInt32(q.Question_Id);
Checked = q.Checked;
if (q.Question_Type == 11) //indicates its objective Question
{
//ill bind data to checkboxes
}
else if (q.Question_Type == 12) // indicate its fill in the blanks question
{
for (int j = 0; j < que.Length; j++)
{
if (que[j] == '#')
{
count++;
string res = "<input type = 'text' runat = 'server' id ='TxtBoxFillUp" + count + "'/>";
htm = htm.Append(res);
}
else
{
htm = htm.Append(que[j]);
}
}
}
}
Any help will be greatly appreciated, thanks in advance.
Adding control in the way you do it won't create control as asp.net creates it. You do have to create controls as usual .net object.
TextBox myNewTextBox = new TextBox() {};
// Set all initial values to it
And add this cotrol to placeholder or panel, whatever you use. Keep in mind that asp.net page events fire even if you use update panel, so in order to maintain state and events of newly created controls you have take care of creating such controls long before page's Load event fires. Here is my answer to another simialiar question.
Seeing the requirements you have:
1.) You need to use JavaScript. Since the ASP.NET will not recreate controls which are dynamically added. Dynamically added controls need to be recreated after every postback. This is the reason why your TextBoxes are Lost after every postback.
2.) You can write JavaScript code to Hide and show the textboxes for blank texts since at every button click you can call Client side functions using: OnClientClick() property of buttons.
3.) Also to Get the TextBoxes using ID property, add them in Markup( .aspx ) portion itself.
I pass the row index value into next page when gridview button clicked using this code
if(e.CommandName=="select")
{
int Id = int.Parse(e.CommandArgument.ToString());
//Label1.Text = Id.ToString();
Response.Redirect("~/manclothes1.aspx?Id=" + e.CommandArgument.ToString());
}
but i don't know what code i write in next page to display row data
please can anyone help me
In ASP.NET you don't actually pass code to a new page. Instead you modify the controls on the current page and the ASP.NET framework re-renders the page for you. Instead of the Response.Redirect line you want something like
DataGrid1.EditItemIndex = Id;
In the page_load of manclothes1.aspx you can try
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Id"] != null)
{
var id = Request.QueryString["Id"];
// do something with id variable
...
}
}
You'll probably want to reference whatever code on the current page populates the gridview with data in the first place. Essentially, where the code on the current page gets many rows to populate a gridview, the code on the manclothes1.aspx page will get one row. If it's data from a database, the query will likely be very much the same but with an additional WHERE clause to filter by (I'm assuming) an ID value, which is probably a primary key (or the primary key, if we're talking about only one table).
To put this into context, what the call to Response.Redirect() is doing is telling the client (browser) to issue an entirely new request (a GET request, that is) for an entirely new resource (manclothes.aspx with a query string parameter). So understand that "the next page" knows nothing of the gridview on the current page. Nor should it, really. The request should be handled entirely separate from the current page.
Saving the values in the Lists & works fine.
abc= (ABC)(Session["xml"]);
string ctrlStr = String.Empty;
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("something"))
{
ctrlStr = ctl.ToString();
abc.student[0].marks[j].science.something.Value = Convert.ToDecimal(Request.Form[ctrlStr]);
}
Want to retrieve the values from the saved object when I click on edit button back on the respective dynamic textboxes....
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("studentname"))
{
ctrlStr = ctl.ToString();
(Request.Form[ctrlStr]) = abc.student[0].marks[x].science.studentname.ToString();---Gives an error stating the collection is only readonly
}
}
Request.Form — like the Request object generally — is read-only, reflecting the fact that, by the time you are responding to a request, the request itself cannot be changed. ASP.NET uses the values from the form POST to create server controls on the Page, and these allow you to control the values of the input and other form elements that are written to the Response object.
In your case, the TextBox controls are being generated dynamically, so they are not automatically bound to form values — hence your problem. You will need to keep references to the controls when they are created (or find them afterwards using the FindControl() method) and set their Text property.
(original answer follows)
The Controls collection becomes read-only at a certain point in the construction of the page. You have to do manipulation before that point. I don't remember offhand when it is, but you're safe with OnLoad through OnPreRender.
Where is your code firing from?
Update: Okay, I see what you're trying to do. This will be easiest if you're dealing with server-side controls (that is, controls generated by ASP.NET. That would look like this in your aspx (or ascx):
<asp:TextBox runat="server" ID="studentname"/>
Then you could update the value like this:
abc = (ABC)(Session["xml"]);
studentname.Text = abc.student[0].marks[j].science.something.Value.ToString();
That will set the value of the studentname text box automatically without needing to search through all of the Request.Form items. (Assuming you set j somewhere... I don't know the context for that.)
I can't tell for sure from your code, but it looks like you may just have a "plan HTML" input, which would look more like this:
<input type="text" name="studentname"/>
In that case, there is no simple way to update the value from your page's code, so I'd start by making sure that you're using server-side controls.
You can set the Request.Form values with reflection:
Request.Form.GetType().BaseType.BaseType.GetField("_readOnly", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(Request.Form, false);
Request.Form["foo"] = "bar";
What you are trying to achieve?
The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method. - http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
I have a GridView on ASP.NET web form which I have bound to a data source and set it to have 10 records per page.
I also have a hyper link column on the GridView, such that a user can navigate to another page (details page) from the list. On the details page, they have "Back" button to return to the GridView page
Edit
Just to clarify the query
I am looking for sample code snippet on the Server Side on how to specify the page index to set the GridView after data binding. The idea is to ensure the user navigates to the same page index they were on.
The three basic options at your disposal: query string, session, cookie. They each have their drawbacks and pluses:
Using the query string will require you to format all links leading to the page with the gridview to have the proper information in the query string (which could end up being more than just a page number).
Using a session would work if you're sure that each browser instance will want to go to the same gridview, otherwise you'll have to tag your session variable with some id key that is uniquely identifiable to each gridview page in question. This could result in the session management of a lot of variables that may be completely undesirable as most of them will have to expire by timeout only.
Using a cookie would require something similar where cookie data is stored in a key/data matrix (optimized hash table might work for this). It would not be recommended to have a separate cookie name for each gridview page you're tracking, but rather have a cookie with a common name that holds the data for all gridview pages being tracked and inside that have the key/value structure.
Edit: A small code snippet on setting the page index.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
try
{
if(HttpContext.Current.Request["myGVPageId"] != null])
{
myGridview.PageIndex = Convert.ToInt32(HttpContext.Current.Request["myGVPageId"]);
}
}
catch(Exception ex)
{
// log it
}
}
}
I'm more of a fan of the Session approach, personally. Simply save your page index as a session variable, and, if this Session variable isn't null on page load, use it to fire your "OnPageIndexChanging" method, like so:
Set your current page number whenever the page number changes:
protected void GridViewIndexChanging(object sender, GridViewPageEventArgs e)
{
myGridView.PageIndex = e.NewPageIndex;
Session["pageNumber"] = e.NewPageIndex;
//whatever your page index changing does...
}
Then, on Page_Load do something like:
if (!IsPostBack)
{
if (Session["pageNumber"] != null)
{
GridViewIndexChanged(myGridView, new GridViewPageEventArgs((int)Session["pageNumber"]));
}
}
you can ues the Page Index Change Event of Gridview and Find out the Current Page Index for e:g
yourGridId.PageIndex=e.NewPageIndex;
ViewState["GridPageIndex"]=e.NewPageIndex;
on PageLoad Get the Viewstate Value
string pIndex=string.Empty;
pIndex=Convert.toInt32(ViewState["GridPageIndex"]);
if(!string.Empty(pIndex))
{
yourGridId.PageIndex =pIndex;
}
you must use query string and is recommended, otherwise you can use session object but don't use that for this as you may have grid view opening in different pages so use query string .
gridView1.CurrentPageIndex = (Request["pageNo"] != null) ? Request["pageNo"] as int : 0;
gridView1.DataSource = myDataSet;
gridView1.DataBind();
you can update your link on GridView_DataBound event
I want to instantly update a status line indicating the number of checked checkboxes across all pages of an asp.net gridview. Right now I am only ably to count the number of checkboxes that are checked on the current gridview page.
Here is my code:
$(document).ready(initAll);
function initAll(){
countChecked();
$(".activeBoxes").click(countChecked);
}
function countChecked() {
var n = $(".activeBoxes input:checked").length;
$("#checkboxStatus").text(n + (n == 1 ? " vehicle is" : " vehicles are") + " selected on this page. ");
if( n == 0){
$(".activateButton").hide();
$("#checkboxStatus").hide();
}else{
$("#checkboxStatus").show();
$(".activateButton").show();
}
}
Keep a hidden text field on your page and everytime you check a box, call a javascript method that will write the 'id' of the checkbox to the hidden field. Each time you postback your page, serialise the hidden field's value to the session in your desired objects structure (be it objects, hash table, array etc).
Upon rendering the page, each checkbox can check the session object structure (that you have created before) and determine if the state of the checkbox was last checked or not.
You could use JQuery to loop through all checkboxes on the page and increment a counter if the checkbox is checked.
You can track the total selection in viewstate (or something similar) on page change. I did something similar tracking the selected row ID's in an array. In my case I had to re-check the items when they returned to the page. Additionally if you allow sorting the selection may move across pages.
Edit: Sorry this doesn't actually your Jquery question, but maybe it will help...
What you're missing is removing the ID. When checking rows and tempid is not checked make sure it is not in saveids.
Do you know that Google is your friend?
Selecting CheckBoxes Inside GridView Using JQuery
The WML Video
And without JQuery but for more perfectionist behavior (like the image below), try this link
alt text http://www.gridviewguy.com/ArticleImages/GridViewCheckBoxTwistAni.gif
I am using a viewstate to keep track of all checked items across all pages and rechecking them upon returning to the page.
I will have to add my viewstate value to the page total and somehow subtract overlapping totals. Since my jquery does not include an id, this will be tricky.
protected ArrayList savedIds;
if (ViewState["SavedIds"] == null) savedIds = new ArrayList();
else savedIds = (ArrayList)ViewState["SavedIds"];
List<int> activateList = new List<int>();
foreach (GridViewRow tt in GridView2.Rows)
{
CheckBox cb = (CheckBox)tt.FindControl("ActivateItem");
HiddenField id = (HiddenField)tt.FindControl("IdField");
if (cb.Checked)
{
int tempId = 0;
string tempId2 = id.Value.ToString();
int.TryParse(tempId2, out tempId);
activateList.Add(tempId);
}
}
foreach (int activateId in activateList)
{
if (!savedIds.Contains(activateId.ToString())) savedIds.Add(activateId.ToString());
}
ViewState["SavedIds"] = savedIds;