Stop DropDownList SelectedIndexChanged Event firing on FormView command - c#

I have a dropdown list inside an editItemTemplate. The Dropdownlist onSelectedIndexChanged event fires on change like I want. However it also will fire when I submit the form.
********UPDATE ************
Per Saechel comment below, I started to investigate further. Here it describes it can be done. http://blog.programmingsolution.net/net-windows-application/selectionchangecommitted-and-selectedindexchanged-events-system-nullreferenceexception-while-closing-windows-form/
BUT, I tried it and it didn't even fire the event.
I checked http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist(v=vs.110).aspx and they don't list the event.
My goal is to let the user enter the values as a % of the Total or actual as actual tons and then toggle back and forth. The end value that will be inserted into the DB will be in tons.
I want to either:
a) not fire the "onSelectedIndexChanged" event
b) Some how determine if I am on the same index and have an if statement to skip everything
c) A better way of going about this that I don't know of.
I tried verifying via the ViewState the Dropdown's current index and skip the code if it was the same but couldn't find the value. Maybe help me figure out how to get that value? Searched around and could not find how do do it.
I tried: `var vs = ViewState["ddl_units"].ToString(); and some other variations as I needed to find the control via FindControl
.aspx:
<asp:Panel ID="pnlRecycledMaterialsReceivedForm" runat="server" Visible="false">
<asp:FormView ID="fvAddRecycledMaterialsReceived" runat="server" SkinID="annualReportFormview" EnableViewState="false"
HeaderText="Selected Recycled Materials Received Detail" DataKeyNames="RecycleDetailId" DefaultMode="Insert"
DataSourceID="odsRecycledMaterialsReceivedDetail" OnDataBound="fvAddRecycledMaterialsReceived_DataBound"
OnItemCommand="fvAddRecycledMaterialsReceived_ItemCommand" OnItemInserted="fvAddRecycledMaterialsReceived_ItemInserted"
OnItemUpdated="fvAddRecycledMaterialsReceived_ItemUpdated" OnItemDeleted="fvAddRecycledMaterialsReceived_ItemDeleted">
<EditItemTemplate>
<asp:TextBox ID="tbxRecycledTotalWasteQuantity" runat="server" Text='<%# Bind("TotalWasteQuantity") %>' Width="64px"></asp:TextBox>
<asp:TextBox ID="tbxRecycledWasteCommercialQuantity" runat="server" Text='<%# Bind("CommercialQuantity") %>' Width="64px"></asp:TextBox>
<asp:TextBox ID="tbxRecycledWasteResidentialQuantity" runat="server" Text='<%# Bind("ResidentialQuantity") %>' Width="64px"></asp:TextBox>
<asp:DropDownList ID="ddl_Units" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_Units_SelectedIndexChanged">
<asp:ListItem Value="" Text="" Enabled="false" />
<asp:ListItem Text="Tons" Value="1" />
<asp:ListItem Text="Percent" Value="9" />
</asp:DropDownList>
<asp:LinkButton ID="lbtnWasteReceivedUpdate" runat="server" Text="Update" CommandName="Update"
ValidationGroup="RecycledWasteReceivedDetail" Font-Bold="True" />
<asp:LinkButton ID="lbtnWasteReceivedInsertCancel" runat="server" Text="Cancel" CausesValidation="False" CommandName="Cancel" />
</EditItemTemplate>
</asp:FormView>
</asp:Panel>
.cs:
protected void ddl_Units_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox tbxRecycledTotalWasteQuantity = (TextBox)fvAddRecycledMaterialsReceived.FindControl("tbxRecycledTotalWasteQuantity");
TextBox tbxRecycledWasteResidentialQuantity = (TextBox)fvAddRecycledMaterialsReceived.FindControl("tbxRecycledWasteResidentialQuantity");
var d_TotalWasteQuantity = Convert.ToDecimal(tbxRecycledTotalWasteQuantity.Text);
ResidentialQuantity = Convert.ToDecimal(tbxRecycledWasteResidentialQuantity.Text);
DropDownList ddl_units = (DropDownList)fvAddRecycledMaterialsReceived.FindControl("ddl_units");
if (ddl_units.SelectedIndex.ToString() == "2")
{
//2 = percent
//Take tb value and convert to percent
//300/700 * 100
tbxRecycledWasteResidentialQuantity.Text = ((ResidentialQuantity / d_TotalWasteQuantity) * 100).ToString();
//ResidentialQuantity = ResidentialQuantity * (d_TotalWasteQuantity / 100);
}
else
{
//Else 'tons' was chosen. Convert value(%) to tons.
//700 * (43/100) = 301
ResidentialQuantity = d_TotalWasteQuantity * (ResidentialQuantity / 100);
tbxRecycledWasteResidentialQuantity.Text = ResidentialQuantity.ToString();
//tbxRecycledWasteResidentialQuantity.Text = "Tons";
}
}

Try using the SelectionChangeCommitted Event.
This will not trigger on form load but triggers on selectionchange

Related

ASP.NET Web Forms: How to reference CheckBoxList items as 'selected' on a table on another page using only C# and ASP.NET web forms?

Assignment Instructions:
Develop a simple shopping cart application that uses session objects to store the information. You will have to create an ASP.NET project that contains two web forms. The first web form, ShoppingCart.aspx, allows the user to select items using a set of checkboxes. This page shows also the number of items in the cart.
The second web form, Display.aspx, displays the number of selected items in a table and allows the user to go back to the first web form and continue shopping.
I am using a CheckBoxList to list my products, and I built a table with IDs in the cells to receive the data the user checks off.
(I considered the idea of using CheckBox vs. CheckBoxList, but this would not be the appropriate solution and doesn't easily allow counting total items selected)
I have tried using cookies and session state variables, but I can't figure out how to associate them to the table.
I can transfer test data from labels and textboxes, anything with an ID, but not my CheckBoxList items.
How do I reference which checkboxes are selected on page 1, that will update the desired table cells on page 2, after clicking the 'checkout' button without unique IDs on the list items?
Example: If... 1lb Dark Roast is selected on page 1 ...
(identified as 'p001' for product 1 on next page)
<asp:ListItem Value="15.99">1lb Dark Roast</asp:ListItem>
On page 2 (Display.aspx) the Amount column should update to '1' beside that product
<asp:TableCell ID="p001_amt" runat="server"></asp:TableCell>
If an item is checked on page 1, this should be the result... (along with the other products).
Product
Price
Amount
1lb dark Roast
$15.99
1
1lb Med Roast
$15.99
0
1 = checked, 0 = unchecked (assignment desired outcome shows this table)
Any help would be appreciated. Thanks.
Here are snippets from my code, if more is needed I can add a link to the full pages.
Page 1 (ShoppingCart.aspx)
ShoppingCart.aspx
------------------
<asp:Label ID="TotalCart_lbl" runat="server" Text="Total Items in your Cart: "></asp:Label>
<br />
<asp:CheckBoxList ID="Shop_ckbx" runat="server">
<asp:ListItem Value="15.99">1lb Dark Roast</asp:ListItem>
<asp:ListItem Value="15.99">1lb Medium Roast</asp:ListItem>
<asp:ListItem Value="12.99">1lb Decaf Roast</asp:ListItem>
<asp:ListItem Value="16.99">1lb Cold Brew</asp:ListItem>
<asp:ListItem Value="10.99">1 box Tea</asp:ListItem>
<asp:ListItem Value="35.99">French Press</asp:ListItem>
<asp:ListItem Value="8.99">CCM Mug</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button ID="UpdateCart_btn" runat="server" Text="Update Your cart" OnClick="UpdateCart_btn_Click"/>
<br />
<asp:Label ID="Contents_lbl" runat="server" Text="Update To See Cart Contents"></asp:Label>
<br />
<asp:Label ID="Cost_lbl" runat="server" Text="Total: "></asp:Label>
<br />
<asp:Button ID="Checkout_btn" runat="server" PostBackUrl="~/Display.aspx" Text="Go to Checkout" />
ShoppingCart.aspx.cs
---------------------
protected void UpdateCart_btn_Click(object sender, EventArgs e)
{
int total = 0; //Total item count
Contents_lbl.Text = "Your Cart Contains: <br/>- - - - - - - - - - - - - - - -";
foreach (ListItem listItem in Shop_ckbx.Items)
{
if (listItem.Selected == true)
{
//Add Text to label
Contents_lbl.Text += "<br/>&#8226 " + listItem.Text;
//Count Items in Cart
total += 1;
}
}
Contents_lbl.Text += "<br/>";
for (int i = 0; i < Shop_ckbx.Items.Count; i++)
{
if (Shop_ckbx.Items[i].Selected)
{
cost += Convert.ToDouble(Shop_ckbx.Items[i].Value);
Cost_lbl.Text = "Total: $ " + cost.ToString();
}
}
//Update total items
TotalCart_lbl.Text = "Total Items in Your Cart: " + total;
}
protected void Checkout_btn_Click(object sender, EventArgs e)
{
How do I reference the items in the checklist on page 1
to update the table on page 2 without unique IDs on each list item?
}
Page 2 code (Display.aspx)
Display.aspx
------------------
<asp:Table ID="Display_tbl" runat="server">
<asp:TableRow runat="server" ID="Header_row" Font-Bold="True" Font-Size="Larger" BackColor="#FFCC99">
<asp:TableCell ID="Product_cell" runat="server" Width="250">Product</asp:TableCell>
<asp:TableCell ID="Price_cell" runat="server" Width="100">Price</asp:TableCell>
<asp:TableCell ID="Amount_cell" runat="server" Width="100">Amount</asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p001">
<asp:TableCell ID="p001_prod" runat="server">1lb Dark Roast</asp:TableCell>
<asp:TableCell ID="p001_price" runat="server">$ 15.99</asp:TableCell>
<asp:TableCell ID="p001_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p002" Width="500px">
<asp:TableCell ID="p002_prod" runat="server">1lb Med Roast</asp:TableCell>
<asp:TableCell ID="p002_price" runat="server">$ 15.99</asp:TableCell>
<asp:TableCell ID="p002_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p003">
<asp:TableCell ID="p003_prod" runat="server">1lb Decaf</asp:TableCell>
<asp:TableCell ID="p003_price" runat="server">$ 12.99</asp:TableCell>
<asp:TableCell ID="p003_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p004">
<asp:TableCell ID="p004_prod" runat="server">1lb Cold Brew</asp:TableCell>
<asp:TableCell ID="p004_price" runat="server">$ 16.99</asp:TableCell>
<asp:TableCell ID="p004_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p005">
<asp:TableCell ID="p005_prod" runat="server">1 box Tea (50 bags)</asp:TableCell>
<asp:TableCell ID="p005_price" runat="server">$ 10.99</asp:TableCell>
<asp:TableCell ID="p005_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p006">
<asp:TableCell ID="p006_prod" runat="server">French Press</asp:TableCell>
<asp:TableCell ID="p006_price" runat="server">$ 35.99</asp:TableCell>
<asp:TableCell ID="p006_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="p007">
<asp:TableCell ID="p007_prod" runat="server">CCM Coffee Mug</asp:TableCell>
<asp:TableCell ID="p007_price" runat="server">$ 8.99</asp:TableCell>
<asp:TableCell ID="p007_amt" runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="Total_row">
<asp:TableCell ID="Total_prod" runat="server">Total</asp:TableCell>
<asp:TableCell ID="Total_price" runat="server"></asp:TableCell>
<asp:TableCell ID="Total_amt" runat="server"></asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:LinkButton ID="Back_linkbtn" runat="server" OnClick="Back_linkbtn_Click">Go Back to the Shop</asp:LinkButton>
Display.aspx.cs
-------------------
protected void Page_Load(object sender, EventArgs e)
{
ShoppingCart prevPage = PreviousPage as ShoppingCart;
if (prevPage != null)
{
NOT SURE HOW TO LINK TO MY CHECKLIST ITEMS
TO UPDATE 'AMOUNT' TABLE CELLS
Also,
CHECKBOXES ON PREVIOUS PAGE NEED TO STAY SELECTED
in order to CONTINUE SHOPPING.
}
}
protected void Back_linkbtn_Click(object sender, EventArgs e)
{
Response.Redirect("ShoppingCart.aspx");
}
Ok, so the problem we have here is of course matching up the “thing” you selected on one page, and then figuring this out on the next web page.
To be fair, the problem here is that no doubt you have to "make up" the data here. And that REALLY hurts this whole process, since you having to type in the data two times (once on this page, and then on the target page). Worse, you have to match up by "text". One little space, period etc. and your whole system will fall down.
I going to suggest we NOT worry and NOT have to match up the values. We can in one shot get rid of a HUGE problem, and ALSO reduce the markup, the code and all your life hassles (well, ok, just the coding part - can't fix everything!!!).
So, I going to suggest that in place of the check box "list", we create a table and use that for BOTH pages. This will then not only keep us out of rooms with padded walls, but we can deal with a "row" of something that you select, and just not give one hoot as to the spelling or even what we place in that row. And by doing this, you could with almost no code changes change the "list" from our table to a database - and the whole she-bang would work!!
So, lets use (create) a table, and not only is this easy, but I think far more clean to setup our data.
So, we will have this at the start of the page (a table and some total values for the WHOLE page class.
public class MyFirstOrderPage : System.Web.UI.Page
{
private DataTable MyTable = new DataTable();
private decimal MyTotal = 0;
private int MyTotalQty = 0;
Ok, now lets do the sub in this page to load up the above table.
public void CreateData()
{
MyTable.Columns.Add("Product", typeof(string));
MyTable.Columns.Add("Price", typeof(decimal));
MyTable.Columns.Add("Qty", typeof(int));
MyTable.Columns.Add("Amount", typeof(decimal));
MyTable.Columns.Add("Purchased", typeof(bool));
MyTable.Rows.Add({"11b Dark Roast",15.99,1,0,false});
MyTable.Rows.Add({"11b Medium Roast",15.99,1,0,false});
MyTable.Rows.Add({"1b Decaf Roast",12.99,1,0,false});
MyTable.Rows.Add({"11b Cold Brew",16.99,1,0,false});
MyTable.Rows.Add({"1 box Tea Brew",10.99,1,0,false});
MyTable.Rows.Add({"French Press",35.99,1,0,false});
MyTable.Rows.Add({"CCM Mug",8.99,1,0,false});
}
Now not only can you "easy" read the above, but you can change/view and see the columns and then the data follows - so you can see we decided to have a Qty and also a column for the purchased. this will save BUCKETS of code, and BUCKETS of markup. And we can use the above to BOTH pages - no having to have two copies of this list!!!!
Ok, so now we have our table. next up, lets display that table. And we can use VERY much the same grid in our order page as we can in the check out page (saves even more time, more code and even MORE markup!!!).
So, lets use a gridview. We could use a listview and I would consider that if you wanted a cute picture and some more product description. But, gridview is fine.
So, here is the markup for the gridview:
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" ShowFooter="true"
Font-Bold="True" Font-Size="Larger" BackColor="#FFCC99" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" Headerstyle-width="250px" />
<asp:BoundField DataField="Price" DataFormatString="{0:C2}" HeaderText="Price" Headerstyle-width="80px" />
<asp:TemplateField HeaderText="Qty" >
<ItemTemplate>
<asp:TextBox ID="Qty" runat="server" Width="60px"
Text ='<%# Eval("Qty") %>'
MyRow = '<%# Container.DataItemIndex %>'
AutoPostBack="true" OnTextChanged="Qty_TextChanged"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="Amount" runat="server" width="80px"
Text ='<%# FormatCurrency(Eval("Qty") * Eval("Price")) %>' Enabled="false" DataFormatString="{0:C2}" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Purchase" ItemStyle-HorizontalAlign="Center">
<ItemTemplate >
<asp:CheckBox ID="CheckBox1" runat="server" width="110px"
Checked ='<%# Eval("Purchased") %>'
MyRow = '<%# Container.DataItemIndex %>'
AutoPostBack="true"
OnCheckedChanged="CheckBox1_CheckedChanged1"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:HiddenField ID="qtycheck" runat="server" ClientIDMode="Static" />
<br />
<asp:Button ID="Checkout_btn" runat="server" Text="Proceed to Checkout"
style="width:140px;height:60px;background-color:#FFCC99;border-radius:25px"
OnClientClick="hasorder();return false;"/>
<script>
function hasorder() {
var CheckQty = document.getElementById("qtycheck")
if (CheckQty.value > 0) {
window.location.href = "/CheckOut.aspx"
}
else {
alert("Please select at least one Purchase before proceding to check out");
return false;
}
}
</script>
Now that is a bit of markup, but it is STILL much less then say your 2nd page table, and better you see how our 2nd page now is VERY little markup!!
Ok, so we have the above. The only real issue is that when you check a box, we need to total things up. And when you edit or change the qty, then SAME thing - update the totals.
So, the code we have for each part is again rather limited. I'll post in all in one shot:
protected void Page_Load(object sender, System.EventArgs e)
{
if (System.Web.UI.Page.IsPostBack == false)
{
// ok first page load, now check if reutrn from checkout
if (System.Web.UI.Page.Session["MyTable"] == null)
{
CreateData(); // first time here - create the data
System.Web.UI.Page.Session["MyTable"] = MyTable; // save the data table
}
else
// we have data - (so this is user change of mind from checkout page)
MyTable = System.Web.UI.Page.Session["MyTable"];
// ok, now load our data into the grid
LoadData(); // load the data
}
else
// this is a post back due to general changes and selections for this
// page under normal and mutliple operations and choices by the user.
// we dont' need to re-display the grid - it persists automatic
// however the datatable variable does NOT persist - so get from session
MyTable = System.Web.UI.Page.Session["MyTable"];
}
public void LoadData()
{
MyTotal = 0;
MyTotalQty = 0;
qtycheck.Value = 0;
GridView1.DataSource = MyTable;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox MyAmount = e.Row.FindControl("Amount");
DataRow MyRow = MyTable.Rows(e.Row.RowIndex);
MyRow("Amount") = MyRow("Qty") * MyRow("Price");
if (MyRow("Purchased") == true)
{
// total up the qty purcchased and the amount
MyTotal += MyRow("Amount");
MyTotalQty += MyRow("Qty");
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
// this is our bottom last footer.
e.Row.Cells(3).Text = Strings.FormatCurrency(MyTotal);
e.Row.Cells(2).Text = MyTotalQty;
e.Row.Cells(1).Text = "Totals:";
qtycheck.Value = MyTotalQty; // a hidden control - to check for qty > 0 on checkout
}
}
protected void CheckBox1_CheckedChanged1(object sender, EventArgs e)
{
// user click on purchase a row - udpate totals.
CheckBox cBox = sender;
int RowID = cBox.Attributes("MyRow");
MyTable.Rows(RowID).Item("Purchased") = cBox.Checked;
// data table has been changed - so we call the load data routine to udpate
// our grid
LoadData();
}
protected void Qty_TextChanged(object sender, EventArgs e)
{
// user changed the qry in a row
TextBox tBox = sender;
int RowID = tBox.Attributes("MyRow");
MyTable.Rows(RowID).Item("Qty") = tBox.Text;
// data table has been changed - so we call the load data routine to udpate
// our grid
LoadData();
}
}
Now that is a "bit" of code, but again, not really much.
So, you now get this after running:
So, notice what we do WHEN you check a box!
We simple do this:
protected void CheckBox1_CheckedChanged1(object sender, EventArgs e)
{
// user click on purchase a row - udpate totals.
CheckBox cBox = sender;
int RowID = cBox.Attributes("MyRow");
MyTable.Rows(RowID).Item("Purchased") = cBox.Checked;
// data table has been changed - so we call the load data routine to udpate
// our grid
LoadData();
}
So, now NO MATCHING problem really exists, does it? You click on a row, and we simply change the Purchased setting (a true/false flag). And that is it - done! no matching required. When you thus check a box, we change the table value, and then simply say to the code will you please re-display the data!!! So NOW we are SAVING all that matching work!!!
Now, the check out code becomes a walk in the park.
when you click on the button to check out, we jump to the checkout page.
The markup is now dead simple - since it much the same as the first page - but no ability to change things. Hence this:
<asp:GridView ID="GridView2" runat="server" ShowFooter="true"
Font-Bold="True" Font-Size="Larger" BackColor="#FFCC99"
AutoGenerateColumns="False"
>
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" Headerstyle-width="250px" />
<asp:BoundField DataField="Price" DataFormatString="{0:C2}" HeaderText="Price" Headerstyle-width="80px" />
<asp:BoundField DataField="Qty" HeaderText="Qty" Headerstyle-width="80px" />
<asp:BoundField DataField="Amount" HeaderText="Amount" Headerstyle-width="80px" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:Button ID="ChangeOrder_btn" runat="server" PostBackUrl="~/SimpleButton.aspx" Text="Change order"
style="width:140px;height:60px;background-color:#FFCC99;border-radius:25px"
/>
<br />
</div>
And the page looks like:
So, you NOW see why we using a table - since the SAME data now drives both pages, and our problem becomes smaller and smaller - not larger and larger!!
And our code for that checkout page, it is this:
class CheckOut : System.Web.UI.Page
{
private decimal MyTotal = 0;
private int MyTotalQty = 0;
protected void Page_Load(object sender, System.EventArgs e)
{
DataTable MyTable = System.Web.UI.Page.Session["MyTable"];
DataView dv = new DataView(MyTable); // we use data view in palce of data table - it can fitler!!
dv.RowFilter = "Purchased = True";
GridView2.DataSource = dv;
GridView2.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
MyTotal += e.Row.Cells(3).Text;
MyTotalQty += e.Row.Cells(2).Text;
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells(3).Text = Strings.FormatCurrency(MyTotal);
e.Row.Cells(2).Text = MyTotalQty;
e.Row.Cells(1).Text = "Totals:";
}
}
}
So, by build a better design and mouse trap with the first page, and a better approach, then the next page becomes VERY simple, since we re-use the data, re-use the table and in fact darn near re-used the grid too!!!
And to display the order we ONLY have to get the table, and filter the results by purchased.
And the button to go back and change your mind? Well, it just jumps back to the that order page.
So while we did have to build up a bit more "markup" in the first page, we reduced by huge amounts the markup in the 2nd page.

asp:label change visibility after hiding it

I've got an asp:Label and a asp:DropDownList that I want to be able to switch back and forth between visible and invisible when clicking on some buttons. Right now, my code looks like
aspx file
<asp:Label AssociatedControlID="statusFilter" id="statusFilterLabel" runat="server" CssClass="filterLabel">Status
<asp:DropDownList ID="statusFilter" runat="server" CssClass="filterInput" AutoPostBack="true" OnSelectedIndexChanged="anyFilter_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value=" 0"><All></asp:ListItem>
</asp:DropDownList>
</asp:Label>
<asp:Button Text="ALL" ID="AllTabButton" CssClass="tabButton" runat="server" OnClick="AllTab_Click" />
<asp:Button Text="Arrived" ID="ArrivedTabButton" CssClass="tabButton" runat="server" OnClick="ArrivedTab_Click" />
code behind
protected void AllTab_Click(object sender, EventArgs e)
{
AllTabButton.CssClass = "tabButtonClicked";
ArrivedTabButton.CssClass = "tabButton";
statusFilter.Visible = true;
statusFilterLabel.Visible = true;
}
protected void ArrivedTab_Click(object sender, EventArgs e)
{
AllTabButton.CssClass = "tabButton";
ArrivedTabButton.CssClass = "tabButtonClicked";
statusFilter.Visible = false;
statusFilterLabel.Visible = false;
}
The only problem is that if I try to set Visible=true after setting Visible=false it would give me an error Unable to find control with id 'statusFilter' that is associated with the Label 'statusFilterLabel'.
I tried doing some other things instead of using Visible, like setting the style: statusFilter.Style.Add("display", "block") and setting the cssclass: statusFilter.CssClass = "displayBlock"but the resulting error always showed up.
An asp:Panel would work, but I'm avoiding using that because I want my asp:Label and asp:DropDownList to line up with several other labels and dropdownlists; putting in a panel would make them not line up properly.
I'm guessing there is something I'm missing, something I just don't get, but I can't seem to figure out what that is. If anybody has any clue as to what's happening, I would really appreciate the help!
It's not able to always find the control on postback because it's a child of statusFilter. Move the input field outside of the label:
<asp:Label AssociatedControlID="statusFilter" id="statusFilterLabel" runat="server" CssClass="filterLabel">Status
</asp:Label>
<asp:DropDownList ID="statusFilter" runat="server" CssClass="filterInput" AutoPostBack="true" OnSelectedIndexChanged="anyFilter_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value=" 0"><All></asp:ListItem>
</asp:DropDownList>

asp.net Dropdownlist Customvalidator servervalidate referencing control

I have a dropdownlist that I populate from the DB, and depending on business logic I need to be able to validate the selected item (TEXT) from the dropdownlist with server side vaildation. Requirements state I cannot simply filter it out as part of the SQL statement. The solution I have been trying to get to work is to simply create a customvalidation in the code behind.
The validation is called, BUT I cannot figure out how to reference the ddl DataTextField value for the item selected. When I try and do the server side code below the asp.net system states that my dropdownlist does not exist within the detailsview and provides a red underline as a result. In this instance it will always be insertmode.
Suggestions
ASP Code
<asp:DetailsView ID="dtlSample" runat="server" AutoGenerateEditButton="true" AutoGenerateRows="false">
<Fields>
.
.
.
<asp:TemplateField HeaderText="Position">
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPosition" runat="server" AutoPostBack="True"
LDataSource="Select Position, PositionId from ...." DataTextField="Position" DataValueField="PositionId"
></asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="ddlPosition" runat="server" AutoPostBack="True"
LDataSource="Select Position, PositionId from ...." DataTextField="Position" DataValueField="PositionId"
></asp:DropDownList>
</InsertItemTemplate>
<asp:CustomValidator ID="cvPos" Display="Dynamic" ControlToValidate = "DDLPosition"
OnServerValidate="ddlPos_Check" runat="server" ForeColor="Red" ErrorMessage="My error message"></asp:CustomValidator>
</asp:TemplateField>
</Fields>
CODE BEHIND
protected void ddlPos_Check(object sender, ServerValidateEventArgs args)
{
if (ddPosition.SelectedItem.Text.Contains("some value")
args.IsValid = false;
else
args.IsValid = true;
}
Murphy's law, answer your own question a few hours after.
DropDownList ddlList=DetailsView2.FindControl("ddlPosition") as DropDownList;
if (ddlList != null)
{
if (ddlList.SelectedItem.Text.Contains("text")) {
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

I want the textbox AJAX Mask Edit Extender to change based on a radio button selection

I creating an ASP.net online application with C# background. I am also using AJAX MaskEditExtender. I'm pretty new to AJAX and don't know Javascript. What I need to do is have the textbox AJAX mask change based on the selection of the radio buttons.
In this example they are choosing salary or hourly. I need the salary to be "999,999" and the hourly to be "99.99".
<asp:TextBox ID="finalwage" runat="server" Width="80px">$</asp:TextBox>
<!-- Salary Mask -->
<asp:MaskedEditExtender
ID="MaskedEditExtender1"
runat="server"
TargetControlID="finalwage"
Mask="999,999"
MessageValidatorTip="true"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="None"
ErrorTooltipEnabled="true">
</asp:MaskedEditExtender>
<asp:MaskedEditValidator
ID="MaskedEditValidator1"
runat="server"
ControlExtender="MaskedEditExtender1"
IsValidEmpty="true"
MinimumValue="0"
MaximumValueMessage="Must enter a number"
ControlToValidate="finalwage" >
</asp:MaskedEditValidator>
<!-- Hourly Mask -->
<asp:MaskedEditExtender
ID="MaskedEditExtender2"
runat="server"
TargetControlID="finalwage"
Mask="99.99"
MessageValidatorTip="true"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="None"
ErrorTooltipEnabled="true">
</asp:MaskedEditExtender>
<asp:MaskedEditValidator
ID="MaskedEditValidator2"
runat="server"
ControlExtender="MaskedEditExtender1"
IsValidEmpty="true"
MinimumValue="0"
MaximumValueMessage="Must enter a number"
ControlToValidate="finalwage" >
</asp:MaskedEditValidator>
.......
<asp:RadioButtonList
ID="RadioButtonList1"
runat="server"
AutoPostBack="true"
RepeatDirection="Horizontal"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem Text="Hourly" Value="Hourly"
<asp:ListItem Text="Salary" Value="Salary" />
</asp:RadioButtonList>
Heres the C# code that I thought would work:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedValue = "Hourly")
{
MaskedEditExtender1.Mask = "99.99";
}
if (RadioButtonList1.SelectedValue == "Salary")
{
MaskedEditExtender1.Mask = "999,999";
}
}
Try to move the RadioButtonList1_SelectedIndexChanged code to Page_Init. I believe RadioButtonList1_SelectedIndexChanged is too late in the lifecycle process to change the mask.

Controlling Checkboxes inside a Gridview Row in ASP.NET

Not really sure how to handle this issue but here goes...
I have a gridview with two checkboxes for each row, below is an example of the item template:
<ItemTemplate>
<asp:CheckBox ID="MasterCheckbox" runat="server"/>
<asp:CheckBox ID="ChildCheckbox" runat="server" />
</ItemTemplate>
I would like the 'enabled' property of the ChildCheckbox to be controlled by the 'Checked' property of the MasterCheckbox ... so in other words the ChildCheckbox is only enabled when the MasterCheckbox has been checked.
I know that I will need to append a handler onto the MasterCheckbox control to invoke some javascript to perform the necessary actions on the client-side - this will probably be done in the row_databound() method?
I can't quite figure out the javascript required to get this to work, so any hints/tips would be welcome.
Thanks
Dal
First you dont need to answer your own question,you can add comments into your very first question.
Since you are using GridView , I think you are binding something for MasterCheckBox,
so let's say that it's boolean value in a dataTable.
For Example it's a row contaning column with name IsMasterChecked
You can handle Enabling the other one with binding custom expressions as
<ItemTemplate>
<asp:CheckBox ID="MasterCheckbox" runat="server" />
<asp:CheckBox ID="ChildCheckbox" runat="server" Enabled='<%# Convert.ToBoolean(Eval("IsMasterChecked")) %>'/>
</ItemTemplate>
or
<ItemTemplate>
<asp:CheckBox ID="MasterCheckbox" runat="server" />
<asp:CheckBox ID="ChildCheckbox" runat="server" Enabled='<%# Convert.ToBoolean(Eval("IsMasterChecked")) ? "true" : "false" %>'/>
</ItemTemplate>
Hope this helps.
Off the top of my head, I think what you will have to do is something along the lines of the following...
<asp:TemplateField HeaderText="Checkbox">
<ItemTemplate>
<asp:CheckBox ID="MasterCheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="checkGridViewChkBox" />
</ItemTemplate>
</asp:TemplateField>
With the following code behind.
CheckBox MasterCheckbox;
CheckBox ChildCheckbox;
private void checkGridViewChkBox()
{
int i;
int x = GridView1.Rows.Count;
for (i = 0; i < x; i++) //loop through rows
{
findControls(i);
if (MasterCheckbox.Checked)
{
ChildCheckbox.Enabled = true;
}else{
ChildCheckbox.Enabled = false;
}
}
}
private void findControls(int i)
{
MasterCheckbox = (CheckBox)(GridView1.Rows[i].FindControl("MasterCheckbox"));
ChildCheckbox = (CheckBox)(GridView1.Rows[i].FindControl("ChildCheckbox"));
}
It's not terribly efficient but works ok.

Categories