Accessing Controls in Header/FooterTemplate C# - c#

My problem is I have a button in the FooterTemplate and HeaderTemplate (In a datalist) and I need to disable them / enable them based on a bool. I know about using the ItemDataBound, but with the way the rest of the page is setup that does not work because the only time it is bound is the initial page load.
I at one time had this working using javascript, but something happened and my javascript is no longer doing the job. So I would like to just be able to do it through the codebehind. So is there anyway to use a foreach loop to access the control?
In the events I am trying to do this I have the following loop:
foreach (DataListItem dli in list.Items)
{
int qty = Convert.ToInt32(((TextBox)dli.FindControl("qtyTextBox")).Text);
int productID = Convert.ToInt32(((Literal)dli.FindControl("prodId")).Text);
isQtyValid = COMMONACES.GetValues.getTotalQty(sessionID, productID, qty);
lblError.Visible = !isQtyValid;
lblError.Text = isQtyValid ? string.Empty : "The total quantity for one or more items exceeds the maximum. The total quantity includes items already in the cart.";
Page.ClientScript.RegisterStartupScript(this.GetType(), "function", "SetButtonStatus()", true); //used to access javascript
}
Javascript:
function SetButtonStatus() {
var bb = document.getElementsByClassName('ButtonSubmit');
for (var i = 0; i < bb.length; i++) {
bb[i].disabled = <%=(!isQtyValid).ToString().ToLower()%>;
}
}
I am trying to do this in a text changed event as well as in a selectedindexchanged event if that is helpful info. If any other info is requested I will do my best to provide it.
Thank you for any help you can offer.

Following your code:
Page.ClientScript.RegisterStartupScript(this.GetType(), "function", "SetButtonStatus();", true); //used to access javascript
and in SetButtonStatus()
document.getElementById('<%= ControlButton.ClientID %>').disabled = true/false;
If your code previously worked and has now stopped, make sure you don't have a JavaScript error, i.e. displayed data from data list is causing that problem.
bool isNotValid= false;
foreach (DataListItem dli in list.Items)
{
int qty = Convert.ToInt32(((TextBox)dli.FindControl("qtyTextBox")).Text);
int productID = Convert.ToInt32(((Literal)dli.FindControl("prodId")).Text);
isQtyValid = COMMONACES.GetValues.getTotalQty(sessionID, productID, qty);
lblError.Visible = !isQtyValid;
lblError.Text = isQtyValid ? string.Empty : "The total quantity for one or more items exceeds the maximum. The total quantity includes items already in the cart.";
if(!isQtyValid)
isNotValid=true;
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "function", string.Format("SetButtonStatus('{0}')", isNotValid.ToString().ToLower()) , true); //used to access javascript
function SetButtonStatus(isNotValid) {
var bb = document.getElementsByClassName('ButtonSubmit');
for (var i = 0; i < bb.length; i++) {
bb[i].disabled = isNotValid;
}
}

Related

selected value cleared in postback

I've dynamically bonded select list and when I hit save button then I'm getting value 0 not the selected one.
I'm Using HtmlSelect not Asp:Dropdownlist.
Can anybody help me.?
thanks in advance !!
If you are using html select.,
you use javascript function for change ddl and assign changed ddl value at one hidden field. send that hidden field value to server. Check below code.
function onchangeddl(e) {
var ddl = document.getElementById('ddlid')
for (var i = 0; i < ddl.options.length; i++) {
if (ddl.options[i].text == e.target.options[e.target.options.selectedIndex].text) {
ddl.selectedIndex = i;
ddl.options[i].selectedValue = e.target.options[e.target.options.selectedIndex].value;
ddl.options[i].selected = true;
document.getElementById('<%=hdnfld.ClientID%>').value = e.target.options[e.target.options.selectedIndex].text;
break;
}
}
}
Codebehind.aspx page you have to assign hdnfld value.
I hope its helpful to you.

Field name not found on selected data source - radio button list imageurl

I am getting the following error when I open a particular page of my site on the live web server.
"A field with the name 'imgURL' was not found on the selected data source."
I am using ASP with C# in VS2010. I don't get the error message when I am developing and viewing the page locally.
Both instances point to the same remote database and are executing the same stored procedure. I don't see why I get this message when the page is live on the web server
The function in my code behind calls a stored procedure to populate 5 radio button lists.
For one radio button list, I want to show images on the buttons, hence why I retrieve the "imgURl" field and try bind it to the control. In debug on my local pc I can see, "ID", "DESC" and "imgURL" in the var "resultslist", so the stored procedure does seem to be returning the field OK!
I am obviously puzzled as to why it works locally but not on the main server?
Any help greatly appreciated
protected void BindBookDetailsToRBLBox()
{
ASPxRadioButtonList[] rblList = new ASPxRadioButtonList[5];
rblList[0] = rblInteriors;
rblList[1] = rblBind;
rblList[2] = rblPaper;
rblList[3] = rblLam;
rblList[4] = rblTrim;
// get the current radio button list box values.
// this is called each time the page loads or the control posts a change to its index
int[] bookDetailIDs = new int[] { 0, 0, 0, 0, 0 };
getSelectedRBLBoxValues(ref bookDetailIDs);
for (int i = 0; i < 5; i++)
{
int? returnCode = 0;
if (bookDetailIDs[i] == 0)
{
try
{
var resultsList = db.getValidCombos(RequiredData[i],
bookDetailIDs[0], bookDetailIDs[1],
bookDetailIDs[2], bookDetailIDs[3],
bookDetailIDs[4], ref returnCode).ToList();
// bind the data to the radio button list control
rblList[i].DataSource = resultsList;
rblList[i].ValueField = "ID";
if (i == 4)
rblList[i].ImageUrlField = "imgURL";
rblList[i].TextField = "DESC";
rblList[i].DataBind();
}
catch (SqlException ex)
{
Log_Error.AddToErrorLog("printingbooks.ascx.cs",
"BindBookDetailsToRBLBox", string.Empty, ex.Message);
}
}
}
}
try with below
rblList[i].DataSource = resultsList.Select(x=> new{imgURL =x.imgURL, ID =x.ID}) ;

asp.net Hide Specific items in dropdownlist using javascript

I'm using ASP.NET and I'm dynamically filling up my DropDownList.
Here is my code:
DataTable dtList = new DataTable();
dtList.Columns.Add("Name");
dtList.Columns.Add("Type");
foreach (DataDefinitionResponse dr in _dr)
{
if (dr.Type == "Dropdown")
{
string[] strSplit = dr.ListValue.Split('|');
List<string> lst = new List<string>();
foreach (string word in strSplit)
{
DataRow row = dtList.NewRow();
row["Name"] = word;
row["Type"] = dr.Name;
dtList.Rows.Add(row);
}
}
}
ddlFieldList.DataSource = dtList;
ddlFieldList.DataTextField = "Name";
ddlFieldList.DataValueField = "Type";
ddlFieldList.DataBind();
Now I just want to hide a specific item using Javascript when another DropDownList is selected.
I'm not using SelectedIndexChanged here. I must use Javascript.
Please someone help me with this.
Thx
I don't think you will be able to manipulate the DropDownList with JavaScript and "get away with it" because when the page is subsequently posted back to the server ASP .NET will detect that the DropDownList has been "tampered" with and will throw an exception.
There are flags you can set that stop the error but it is unlikely that you will then be able to use the DropDownList in your code-behind.
You would normally achieve what you are trying to do with SelectedIndexChanged (I know you said you didn't want to) and put the control in an UpdatePanel or similar to avoid a full page post-back / refresh.
function Remove()
{
var DropDownList=document.getElementById('<%=DropDownList1.ClientID%>');
alert(DropDownList.value);
for(i=DropDownList.length-1; i>=0; i--)
{
if(DropDownList.options[i].selected)
{
DropDownList.remove(i);
}
}
}

how to show confirmation dialog from drop down list?

i have a grid which display data from database, and i have a custom column in the left side with checkbox, i choose records to be deleted and i have a dropdown list, which will trigger an event in server side to delete records, before i delete those records i want to show a confirmation dialog like "are you sure? with ok and cancel", how to do that? any thought?
i do this :
if(ddlAction.SelectedValue == "Delete")
{
string id = string.Empty;
int i = 0;
List<int> idx = new List<int>();
foreach (GridViewRow rowitem in gvDept.Rows)
{
CheckBox itemchk = (CheckBox)rowitem.FindControl("cbSelectOne");
if (itemchk != null & itemchk.Checked)
{
id += rowitem.Cells[3].Text.ToString() + ',';
idx.Add(i);
}
i = i + 1;
}
id = id.Trim(",".ToCharArray());
List<string> objRemoveKeys = id.Split(',').ToList();
if (objRemoveKeys.Count > 0)
{
ddlAction.Attributes.Add("OnChange", "javascript:return confirmDeletion('Are you sure you would like to remove the selected items?');"); // this part not working.
AirAsiaLinqDataContext LinqDataCtx = new AirAsiaLinqDataContext();
var record = from a in LinqDataCtx.departements
where objRemoveKeys.Contains(a.departementcode)
select a;
LinqDataCtx.departements.DeleteAllOnSubmit(record);
LinqDataCtx.SubmitChanges();
for (int j = 0; j < idx.Count; j++)
{
gvDept.DeleteRow(idx[j]);
}
}
ddlAction.SelectedValue = "";
}
This looks like code-behind (C#) code. Dialogs happen on the client side. You can do this relatively easily with jQuery (or even vanilla JavaScript code), or use something like the Ajax Control Toolkit's ConfirmButton:
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
For a little more control over the process you can also give JuiceUI a go: http://juiceui.com/controls/dialog
try this
ddlAction.Attributes.Add("onchange", "return confirm('Are you sure you would like to remove the selected items?');");
you should not only show an alert for confirmation but also check if the user has selected some row or not. below code accomplishes both.
javascript function:
function checkIfSelected() {
if (yourGrid.GetSelectedRowCount() == 0) {
alert("You must select atleast one.");
return false;
}
else {
if (confirm("Are you sure you want to proceed?")) { // This is what you want
}
else {
return false;
}
}
}
your dropdownlist:
<asp:DropDownList ID="ddlAction" onChange="javascript:if( checkIfSelected() == false){return false};" AutoPostBack="true" runat="server" OnSelectedIndexChanged="yourID_SelectedIndexChanged">

How to enable disable fields using Java Script in Webform

I have created a web page "Default.aspx" in which I have taken fields:
First Name, Last Name, Account Titling, Titling(radio button list), AccountNumber and AccountFormat
under the "Default.aspx" page, I have used a radio button list also, whose values are Yes and No. If I choose Yes, then the following fields visibility should set to false:
First Name, Last Name
If I choose "NO", then the following fields visibility should set to true:
Account Titling, Account number
For this, I have written the below Java Script code in "Default.aspx"
function EnableDisableTaxID() {
if (document.getElementById("<%=rdOpeningSubAccount.ClientID %>") != null) {
var openSubAccountList = document.getElementById('<%= rdOpeningSubAccount.ClientID %>');
var fbo1RadioList = document.getElementById('<%=fbo1RadioButtonList.ClientID %>').value;
var isOpenSubAccount;
if (openSubAccountList != null) {
var openSubAccount = openSubAccountList.getElementsByTagName("input");
for (var i = 0; i < openSubAccount.length; i++) {
if (openSubAccount[i].checked) {
isOpenSubAccount = openSubAccount[i].value;
alert("Print" + isOpenSubAccount);
}
}
}
alert(typeof(isOpenSubAccount));
if (isOpenSubAccount == 'true') {
FirstName.visible = true;
LastName.visible = false;
AccountTitling.visible = true;
lblFirstName.visible=false;
lblLastName.visible=false;
}
else if (isOpenSubAccount == 'false') {
AccountTitling.visible = true;
AccountNumber.visible = false;
lblAccountTitling.visible = true;
lblAccountNumber.visible = false;
}
}
}
However, I am getting the required value from the Radio button list, however, when I go to check if the selected value of the radiobuttonlist is true, then the code above does not work. I dont know what am I missing. I know that directly using the below code will not work:
if (isOpenSubAccount == 'true') {
FirstName.visible = true;
LastName.visible = false;
AccountTitling.visible = true;
lblFirstName.visible=false;
lblLastName.visible=false;
}
Please help as I m stuck here...
For Visible = false;
document.getElementById('FirstName').style.visibility="hidden";
For Visible = true;
document.getElementById('FirstName').style.visibility="visible";
To Enable:
document.getElementById('FirstName').disabled = false;
To Disable:
document.getElementById('FirstName').disabled = true;
Following can be done for
Non Visible
document.getElementById('id-name').style.display='none';
Visible
document.getElementById('id-name').style.display='block';
Disable
document.getElementById('id-name').setAttribute('disabled', 'disabled');
Enable
document.getElementById('id-name').removeAttribute('disabled');
No; document.getElementById will only get the element with the ID you specify (the HTML spec is quite clear that only one element on a page can have a specific ID).
Each radio button has a different ID attribute, but if you look at the HTML source of a page, you will see that all radio buttons in the list have the same NAME attribute. This is what you should use "the name of the radio button".
onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')"
function GetRadioButtonValue(id)
{
var radio = document.getElementsByName(id);
for (var j = 0; j < radio.length; j++)
{
if (radio[j].checked)
alert(radio[j].value);
}
}

Categories