This is my first web page ever and I can't seem to find the correct way to get the selected index from a dropdown list. I don't need the selected index until the user presses the submit button. I've been testing everything I've found on the subject, but nothing is working.
I don't want the drop-down box to reset when the selection is made, which is what happens if I use postback=true or any selected index changed events. And, I still get an index of 0.
When I test, the selected index is always zero.
This runs on page load:
ddlBudgetLineItem.DataSource = budget.BudgetLineItems;
ddlBudgetLineItem.DataTextField = "Name";
ddlBudgetLineItem.DataValueField = "BudgetLineItemID";
ddlBudgetLineItem.DataBind();
This is the drop-down list:
<asp:DropDownList ID="ddlBudgetLineItem" runat="server">
</asp:DropDownList>
Here is the code that needs the index:
protected void submitPayment()
{
string amountValue = txtAmount.Text.ToString();
float amount = float.Parse(amountValue);
Payment payment = new Payment()
{
Amount = amount,
Payee = txtPayee.Text,
BudgetLineItem = budget.BudgetLineItems[ddlBudgetLineItem.SelectedIndex],
Memo = txtMemo.Text,
PaymentDate = DateTime.Parse(txtPaymentDate.Text),
ExtraUserInfo = info
};
provider.AddPayment(payment);
}
Any assistance is appreciated.
it seems to be a life cycle issue, this is happening because everytime (on a postback or not) the page is loaded, your dropdown is rebuilt (caused by ddlBudgetLineItem.DataBind()), concluding that on a postback your ddl will get index=0 forever.
how can you solve this:
1: Override the page databind method and put your code before call base.databind(); (inside the method)
2: on your load event you just have to call databind (if not is postback), it prevent to rebuild your object states everytime your page is loaded.(cause of your lost information).
3: take a look on a page lifecycle it will help you to prevent future issues like that.
Related
I try to save on Onclientclick to my hiddenfield a string value but it doesnt work I think because of Server.Transfer();
In my is only one control for postback(Dropdownlist) if I change dropdown value I get work Server.Transfer at last in my code.
Here is the code :
$(document).ready(function () {
alert($("[id*=hdnSelectedDiv]").val());
});
function SaveDiv(value) {
$("[id*=hdnSelectedDiv]").val(value);
}
<asp:LinkButton runat="server" CssClass="card-link" ID="lnkGoToLogin" OnClientClick="SaveDiv('dvLogin');return false;" meta:resourcekey="lnkGoToLoginRes"></asp:LinkButton></p>
Here is my OnSelectedIndexChanged :
CurrentSession.SetCurrentLanguage(ddl.SelectedValue);
ddl.SelectedValue = CurrentSession.CurrentLanguage.IetfLanguageTag;
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddl.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddl.SelectedValue);
Server.Transfer(Request.Url.AbsolutePath);
On document ready alert is my value always empty.I try to set value on my document and alert the value it is working.but if I click linkbutton and select any option in my dropdown after postback is my value empty.
How can I solve this I dont want to use Response.Redirect();
That hidden field must have name property.
When the postback occurs, within the server code, is the moment when you can retrieve posted values. This is the time to process them - because, after Server.Transfer starts executing, source context is gone. If you need those values within the target request (the handler transferred to), you need to pass them to it. Your options are: persisted storage (e.g. database), session (might be the best in your case), query.
I have a got Gridview, that gets its data by:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
}
After a button click the database is updated and the new data is shown. Everything works fine.
Now I have to replace the string with an Usercontrol:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
for (int i = 0; i < gridViewer..Rows.Count; i++)
{
UCControl dum = (UCControl)LoadControl("~/UCControl.ascx");
dum.SetData(gridViewer.Rows[i].Cells[0].Text, false);
gridViewer.Rows[i].Cells[0].Controls.Clear();
gridViewer.Rows[i].Cells[0].Controls.Add(dum);
}
}
After first Page_Load(), everything is shown correctly. But when I click my buttons, the Usercontrols do not repaint. The data is set correctly inside, but it does not update.
Because this Control reacts by javascript on UserInputs on the client side, every Usercontrol has got his own Id that is set by
this.ID = "UCControl" + data[0];
data[0] is unique, but known during the whole process.
Can somebody tell me why the UserControl does not repaint? Or better: How do I tell the Usercontrols to update?
From your code I would say that once the data is bound then you can't go in immediately after and start to change it. You would need to hook into one of the databinding events.
If you were using a list viem ItemDataBound would be a good candidate to hook into. But the GridView has a more limited set of events and doesn't offer that level of control - so you are a bit stuck on that score.
In my experience using dynamic controls in asp.net (LoadControl) is just a bit fraught. I think a better option would be to publicly expose a property in your user control and bind to that.
This question gives a good description of how to achieve this
asp.net user controls binds inside gridview
Hope that helps
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.
I write an imagebutton to a table cell in a new row when a user selects an item in a list:
ImageButton imgbtnRemove = new ImageButton();
imgbtnRemove.ID = "uxStandardLetterDeleteImage_" + items.letterName;
imgbtnRemove.CommandName = "uxStandardLetterDeleteImage_" + items.letterName;
imgbtnRemove.ImageUrl = items.remove;
imgStatus.AlternateText = "Remove";
tRow.Cells[3].Controls.Add(imgbtnRemove);
When the new imagebutton is clicked, I can't seem to get a handle to it. I see it in Page_PreRender event, where I also reload the table on each postback.
string returnData = Request.Form.ToString();
but iterating through the form controls images:
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
does not find it. I can find it if I manually put in a:
imgbtnRemove.Click += new System.Web.UI.ImageClickEventHandler(this.ButtonClick);
in the Page_Load and then grab it in the click event:
switch (((System.Web.UI.WebControls.ImageButton)sender).CommandName)
...
but because there are new rows being added and deleted, this gets rather ugly programmatically. I'm thinking there must be an elegant solution to dynamic imagebutton creation and retrieval on the fly from server side code. I've done a lot of digging but this one is stumping me.
Thanks in advance...
If you're creating dynamic controls during the event handling phase of the Page lifecycle (for example, in the item selected event), then the control will be gone on the next postback.
In order for dynamic controls to be registered with ViewState, they have to be created in the Init phase of the event lifecycle.
Also, you say you're iterating through the Form's controls... when you are adding the imagebutton to the table's cells. Are you recursively descending the control heirarchy to look for the imagebutton?
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;