Change button style on page load - c#

This is my table and on this table I have cells in form of buttons. With my css sheet I have made them green.
<asp:Table ID="Table1" runat="server" BorderWidth="2px" BorderColor="#0033cc" BackColor="#ffcccc" >
<asp:TableRow>
<asp:TableCell CssClass="Table-cell-room" ID="D256">D256<br /></asp:TableCell>
<asp:TableCell><asp:Button runat="server" Width="100px" Text="Boka" ID="R1B1" OnClick="Button_Click_First_Row" CssClass="Buttons"/></asp:TableCell>
<asp:TableCell><asp:Button runat="server" Width="100px" Text="Boka" ID="R1B2" OnClick="Button_Click_First_Row" CssClass="Buttons"/></asp:TableCell>
<asp:TableCell><asp:Button runat="server" Width="100px" Text="Boka" ID="R1B3" OnClick="Button_Click_First_Row" CssClass="Buttons"/></asp:TableCell>
<asp:TableCell><asp:Button runat="server" Width="100px" Text="Boka" ID="R1B4" OnClick="Button_Click_First_Row" CssClass="Buttons"/></asp:TableCell>
<asp:TableCell><asp:Button runat="server" Width="100px" Text="Boka" ID="R1B5" OnClick="Button_Click_First_Row" CssClass="Buttons"/></asp:TableCell>
</asp:TableRow>
I have also a Database table called Room and contains Id, Button_id and CheckIfBooked.
Now I want to use my "colum" CheckedIfBook to see if they are booked, meaning CheckedIfBooked = 1.
All of this work but I have no idea to style my buttons on the table which of those who already have CheckedIfBooked = 1.
Meaning that in my Database table I have R1B1 and it's value CheckedIfBooked = 1. But I have no idea to code this in page load. Also I don't want to use
if(Button_id == R1B2){
CheckedIfBooked == 1
//Do some styling on that button
}
Cause I have ALOT of buttons and in my c# code I use sender as new button to get the correct ID from the button clicked.

Possible Solution #1
When rendering the page, add an additional css class to your button if isBooked = true
if (isBooked) {
/// Render the "isBooked" TableCell Button
<asp:TableCell> ... CssClass="isBooked"/></asp:TableCell>
} else {
/// Render the "not Booked" TableCell Button
<asp:TableCell> ... CssClass="Button"/></asp:TableCell>
}
Then in your css:
.isBooked { /* isBooked Button Styles Here */ }
So when your code gets rendered to HTML, the css classes are already in place:
<!-- Example HTML Output -->
< ... class="Button" ... ></>
< ... class="isBooked" ... ></>
< ... class="Button" ... ></>
Possible Solution #2
On page load, have jQuery look for the booked buttons, and disable them, or style them, etc..
$(document).ready(function(){
$("isBooked").each(function(index){
// each isBooked element is now available via $(this)
$(this).addClass("bookedButton");
$(this).prop("disabled", true);
// ...
});
});
Security note: Simply disabling a form button on the client-side (via javascript) isn't enough, you also need to validate data on the server side. So if you disable form elements on the client, make sure your server also verifies that nothing "booked" is trying to be submitted to your form.
Hope this helps.

Related

How to make PopUp window in asp.net web application? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am making a Canteen Management System using ASP.NET Forms.
So I want a Pop-Up window or box which will take input from dropdown list and textbox to implement Filter option.
So how to make it and how to access collected data from code behind?
Any tutorials links or suggestion are all welcome. Thanks for helping :)
There are quite a few ways to do this. If you using the AjaxControlToolKit, they have a fantastic pop up extender, and it takes no JavaScript.
However, probably the best choice is to use jQuery.UI. It is without a doubt your site and application has jQuery, so, I would add jQuery.UI. You can use nueget to install it, or simply go to the jquery site and download the jQuery.UI files. They are common.
So, the way we do this is you create (usually) a "div" on the page that is a popup. This works great since is responds to a "click" very fast (you don't even have to hit the server for the dialog to pop-up. However, the form you pop up might be to edit data.
The next consideration is that popup form cannot have post-backs. (well, ok, it can have one). So if the form you popup is to have some rich verification code, or code that requires some server side event code to run? You tend to be out of luck. So, you can easy pop a form, the user can edit (or enter data), but then you only allowed ONE post-back button event (say "ok - save"). So in most cases such a popup form is fine, but do keep in mind this limitation. If you do need some things to respond in that dialog, then you in most cases have to write ajax calls - that is extra pain and workload for the developer.
So, lets assume we want to pop up a dialog to filter a grid. The popup will allow the user to type in the first few characters of the hotel name OR WE can select a city from a drop down list to filter the grid by city.
and we toss in a show only "active" records with a check box.
So, how would this work, and look? (and keeping the above considerations in mind (only one post-back allowed in the pop dialog).
Well, we first build the grid. But, we need to add some buttons to the heading. So I have to drop a few of the databound fields, and use a template for that one column. This lets us setup the header with a button, or whatever we feel like.
And I did the same for the city heading.
So, we have this markup:
<div id="HotelGrid" runat="server" style="width:50%">
<asp:GridView ID="GHotels" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table table-hover"
style="vertical-align:middle" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="btnSearchCity"
runat="server"
CssClass="btn-default btn-sm"
>City
<span aria-hidden="true" class="glyphicon glyphicon-search"></span>
</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:TemplateField HeaderStyle-Width="200px">
<HeaderTemplate>
<asp:LinkButton ID="cmdSearchHotel"
runat="server"
CssClass="btn-default btn-sm"
OnClientClick="return mysearch(this);"
OnClick="cmdSearchHotel_Click"
>Hotel
<span aria-hidden="true" class="glyphicon glyphicon-search"></span>
</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblHotel" runat="server" Text='<%# Eval("HotelName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description"HeaderText="Description" />
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("Active") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="cmdEdit" runat="server" Text="Edit"class="btn" OnClick="cmdEdit_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now, you can see in above, the markup starts to grow - that's due to gridview requiring "template" around each set of controls. (I often suggest using a listview, since you don't need the template(s). But no big deal.
Ok, so we have the above markup.
My page load code to load the grid? Well, we want the heading to dispaly, so we do it this way:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GHotels.DataSource = MyRst("select * from tblHotels where id = 0")
GHotels.DataBind()
' load the city combo box
cboCity.DataSource = MyRst("SELECT City from tblCity ORDER BY City")
cboCity.DataBind()
cboCity.Items.Insert(0, "") ' allow blank selection
End If
End Sub
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using MyCon As SqlConnection = New SqlConnection(My.Settings.TEST3)
Using cmdSQL As New SqlCommand(strSQL, MyCon)
cmdSQL.Connection.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Ok, so we now see/have this:
Now, the two buttions in the grid heading will have TWO parts.
The part to pop the dialog (jQuery.UI), and then the standard code server side.
Ok so, we have to create a div to hold our pop up.
It will be rather simple, and just combo box (for city), a text box for hotel anme, and a check box for "active only" filter.
so, that div is quite simple. and note when we happy with the div layout, we add display:none to hide the div.
so we have this:
<div id="mysearchdiv" style="border:solid;width:300px;text-align:right;padding:15px;font-size:large;display:NONE">
<p>Select City
<asp:DropDownList ID="cboCity" runat="server" width="150px"
DataTextField="City"
DataValueField="City"
></asp:DropDownList>
</p>
<p>
Hotel Name
<asp:TextBox ID="txtSearchHotel" runat="server" Width="150" Height="25"></asp:TextBox>
</p>
<p>
Include Only Active
<asp:CheckBox ID="chkActiveOnly" runat="server" />
</p>
<asp:HiddenField ID="cmdOption" runat="server" ClientIDMode="Static"/>
</div>
Really very simple markup.
Ok, now the hard part, the jQuery UI is a java script routine, and it is this:
<script>
var searchok = false
function mysearch(btn) {
if (searchok) {
return true
}
var myDialog = $("#mysearchdiv");
myDialog.dialog({
title:"Search For Hotels",
modal: true,
width: "320px",
resizable: false,
appendTo: "form",
autoOpen: true,
buttons: {
Ok: function ()
{
searchok = true
btn.click()
},
Clear: function () {
searchok = true
$('#cmdOption').val('c')
btn.click()
},
Cancel: function () {
myDialog.dialog('close')
}
}
});
return false
}
</script>
So, it is a bit of code, but what jQuery.UI is "grabs" that div, and converts it into a nice dialog. So the end result is this:
Now, either the c# tag was added after I started typing this, or I missed it.
but, the c# code is much the same. The first page load code is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GHotels.DataSource = MyRst("select * from tblHotels where id = 0");
GHotels.DataBind();
// load our search combo box
cboCity.DataSource = MyRst("SELECT City from tblCity ORDER BY City");
cboCity.DataBind();
cboCity.Items.Insert(0,new ListItem("",""));
}
}
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
return rstData;
}
So above will load up the grid (we send it a blank row, since we using the header for searching.
and the buttion click? Well, we pop a jquery dialog. And if it returns true, or false - that determines if the server side buttion will fire.
So, we have this:
<asp:TemplateField HeaderStyle-Width="200px">
<HeaderTemplate>
<asp:LinkButton ID="cmdSearchHotel"
runat="server"
CssClass="btn-default btn-sm"
OnClientClick="return mysearch(this);"
OnClick="cmdSearchHotel_Click"
>Hotel
<span aria-hidden="true" class="glyphicon glyphicon-search"></span>
</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblHotel" runat="server" Text='<%# Eval("HotelName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Note very carefull how we have the jQuery search routine return true ,or false.
Ok, so now it is a simple matter to write that code to filter/search the grid based on that popup.
The code is quite simple, and we "cumulative" add up each search option, or simple skip the options if no value in the search box is entered.
And, we added that hidden field, since as you can see, we can now add more buttons to that dialog, but not have to create new code server side - but just use the one button click to handle all options for that dialog.
And the c# code for this filtering is thus:
protected void cmdSearchHotel_Click(object sender, EventArgs e)
{
if (cmdOption.Value == "c")
{
// clear the search option
cboCity.Text = "";
txtSearchHotel.Text = "";
chkActiveOnly.Checked = false;
cmdOption.Value = "";
GHotels.DataSource = MyRst("select * from tblHotels where id = 0");
GHotels.DataBind();
return;
}
// filter the grid
string strWhere = "";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST3))
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels",con))
{
if (cboCity.Text != "")
{
strWhere += "City = #City";
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = cboCity.Text;
}
if (txtSearchHotel.Text != "")
{
if (strWhere != "")
strWhere += " AND ";
strWhere += "HotelName like #Hotel + '%'";
cmdSQL.Parameters.Add("#Hotel", SqlDbType.NVarChar).Value = txtSearchHotel.Text;
}
if (chkActiveOnly.Checked)
{
if (strWhere != "")
strWhere += " AND ";
strWhere += "Active = 1";
}
if (strWhere != "")
cmdSQL.CommandText += " WHERE " + strWhere;
cmdSQL.CommandText += " ORDER BY HotelName";
con.Open();
GHotels.DataSource = cmdSQL.ExecuteReader();
GHotels.DataBind();
}
So, all in all:
A absoulte min of code.
Not really much more markup then a typical grid.
And I shared a LONG time super cool trick that VERY VERY VERY few have used. That is how to get the one jQuery.UI dialog to NOT fire the server side button if we don't want to. And thus we don't need multiple routines in java, and we don't need multiple routines server side. We simply have the one button call the dialog, and it returns true, or false. But it STILL is running asyncrious as all and most JavaScript widgets should be. (no blocking code allowed!!!).
You can create fied position DIV and show it using JS,JQuery, ... whenever you want to show the dialog.
then you can read input data.
How to generate a simple popup using jQuery

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.

How to hide and display asp:buttons in asp.net from code behind?

I am working on asp.net web application.
In one Page I have two asp buttons.
I want to display them in one condition otherwise I don't want to display them.
So I'm trying to do the same like this. But Its not working.
I can't find the reason behind it. Please tell me where is the issue.
To Hide Buttons
if (!IsPostBack)
{
ButtonReplaceId.Style.Add("display", "none");
ButtonAssociateRules.Style.Add("display", "none");
}
To display buttons
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if(a==0)
{
ButtonAssociateRules.Style.Add("display", "block");
ButtonReplaceId.Style.Add("display", "block");
}
}
aspx for buttons
<div style ="padding-left:400px;">
<asp:Button ID="ButtonAssociateRules" runat="server" OnClick="AssociateMultipleRulesButtonClick"
CssClass="search_button_in_vm_intersection" Text="Associate Multiple Rules"
OnClientClick="return OnClientClickAssociateRewardRuleFile();" />
<asp:Button ID="ButtonReplaceId" runat="server" OnClick="ApplyReplaceIfRuleIntersects"
CssClass="search_button_in_vm_intersection" Text="Replace Previous Rules"
OnClientClick="return OnClientClickReplaceRewardRuleFile();" />
</div>
aspx of button for OnClick event ApplyAssociation()
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Table runat="server" CssClass="rule_file_whole" BorderWidth="0" Style="padding-top: 30px;">
<asp:TableRow ID="MerchantRowAssociation" HorizontalAlign="Center">
<asp:TableCell>
<div style="text-align: center">
<asp:Button ID="AssociationMerchant" Text="Apply Association" runat="server" OnClick="ApplyAssociation"
CssClass="search_button_in_vm_associate1 " OnClientClick="return checkValidation()" />
</div>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
Seeing as you are using a conditional update panel, you can try either of these after putting the buttons inside an update panel.
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if (a == 0)
{
ButtonAssociateRules.Style["visibility"] = "hidden";
ButtonReplaceId.Style["visibility"] = "hidden";
myUpdatePanel.Update();
}
}
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if (a == 0)
{
ButtonAssociateRules.Visible = false;
ButtonReplaceId.Visible = false;
myUpdatePanel.Update();
}
}
Here's an example of your buttons inside an update panel.
<asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div style="padding-left:400px;">
<asp:Button ID="ButtonAssociateRules" runat="server" OnClick="AssociateMultipleRulesButtonClick"
CssClass="search_button_in_vm_intersection" Text="Associate Multiple Rules"
OnClientClick="return OnClientClickAssociateRewardRuleFile();" />
<asp:Button ID="ButtonReplaceId" runat="server" OnClick="ApplyReplaceIfRuleIntersects"
CssClass="search_button_in_vm_intersection" Text="Replace Previous Rules"
OnClientClick="return OnClientClickReplaceRewardRuleFile();" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
You can simple use the Visible property of Button which is more straight forward and clean.
ButtonReplaceId.Visible = false;
If this property is false, the server control is not rendered. You
should take this into account when organizing the layout of your page.
If a container control is not rendered, any controls that it contains
will not be rendered even if you set the Visible property of an
individual control to true. In that case, the individual control
returns false for the Visible property even if you have explicitly set
it to true. (That is, if the Visible property of the parent control is
set to false, the child control inherits that setting and the setting
takes precedence over any local setting.) MSDN.
You are trying to change the state of control in ajax call that is not in current UpdatePanel. Put the buttons in the same UpdatePanel then you will be able to change the state.
ButtonReplaceId.Visible = false;
ButtonAssociateRules.Visible = false;

open a new window on click and without page being postback

i have a page that has a grid with rows of data and it has url hidden in each row n when a row is clicked it opens new tabed window and the parent page still stays open with the grid data. i want to have a button that does the same . my aspx is
<script type="text/javascript" id="igClientScript">
function NavigateOnClick(sender, eventArgs) {
try {
var row = eventArgs.get_item().get_row().get_index();
var url = sender.get_rows().get_row(row).get_cell(0).get_text();
window.open(url);
}
catch (e) {
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Entity"></asp:Label>
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Select Entity</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" ID="EntityName"></asp:Label>
<asp:Button ID="newEntity" runat="server" Visible="false" OnClick="newEntity_Click" OnClientClick="aspnetForm.target ='_blank';" />
<ig:WebScriptManager ID="WebScriptManager1" runat="server"></ig:WebScriptManager>
<ig:WebDataGrid ID="EntityGrid" runat="server" Width="100%" Height="50%" StyleSetName="Claymation" >
<Columns>
</Columns>
<ClientEvents Click="NavigateOnClick" />
</ig:WebDataGrid>
</div>
I want something like window.open =(entity,_newtab) without doing a page post back how can i get this?
Just use
window.open(url, 'random_name');
Refer this: http://www.w3schools.com/jsref/met_win_open.asp
Add an attribute to your button:
target="_blank"
button.attributes.add("target","_blank");
here is what worked part of my problem was that the url is dynamic i created a label that is updated on dropdown selection and pass the label text while creating the url instead of asp button went with html button function opentab(sender, eventArgs) {
try {
var name = document.getElementById('EntityName');
var url = name.textContent;
window.open(url+"Edit.aspx");
}catch(e){
}
}which wont cause a postback

ASP.NET HoverMenuExtender Lazy Loading

I'm trying to get my hovermenuextenders to do some lazy loading. I have avatars across the site that when hovered over should pull back various things (images, recent posts, post count, etc) For obvious reasons I don't want to do this for all avatars on the page_load.
Using the following code I'm able to get the hover event to trigger a postback to the server asynchronously (breakpoint is hit onmouseover). However, the commands in the postback don't seem to be reflected after execution is done. The loading image/label stay in the hover panel. Any help is appreciated!
EDIT: I just realized that the very last avatar rendered on the page works properly but none of the ones above it do. Any ideas what might be causing this strange behavior?
<script language="javascript" type="text/javascript">
function OnHover(image) {
__doPostBack('<%= this.imageHoverTrigger.UniqueID %>', '');
}
</script>
<!-- DUMMY Hover Trigger -->
<input id="imageHoverTrigger" runat="server" style="display:none;"
type="button" onserverclick="imageHoverTrigger_Click" />
<!-- User Avatar -->
<div style="border: solid 1px #AAA; padding:2px; background-color:#fff;">
<asp:ImageButton ID="UserImg" runat="server" />
</div>
<!-- Hover tooltip disabled by default
(Explicitly enabled if needed)-->
<ajax:HoverMenuExtender ID="UserInfoHoverMenu" Enabled="false" runat="server"
OffsetX="-1"
OffsetY="3"
TargetControlID="UserImg"
PopupControlID="UserInfoPanel" dyn
HoverCssClass="userInfoHover"
PopupPosition="Bottom">
</ajax:HoverMenuExtender>
<!-- User Profile Info -->
<asp:Panel ID="UserInfoHover" runat="server" CssClass="userInfoPopupMenu">
<asp:UpdatePanel ID="UserInfoUpdatePanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Image ID="loadingImg" runat="server" ImageUrl="~/Design/images/ajax-loader-transp.gif" />
<asp:Label ID="loadingLbl" runat="server" Text="LOADING..." ></asp:Label>
<asp:Panel ID="UserInfo" runat="server" Visible="false">
<b><asp:Label ID="UserNameLbl" runat="server"></asp:Label><br /></b>
<span style="font-size:.8em">
<asp:Label ID="UserCityLbl" runat="server" Visible="false"></asp:Label> <asp:Label ID="UserStateLbl" runat="server" Visible="false"></asp:Label>
</span>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="imageHoverTrigger" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
UserImg.Attributes.Add("onmouseover", "javascript:OnHover(this)");
}
protected void imageHoverTrigger_Click(object sender, EventArgs args)
{
// Hide loading image/label
loadingLbl.Visible = false;
loadingImg.Visible = false;
//TODO: Set user data here
UserInfo.Visible = true;
}
Figured it out:
My Page_Load event hookup should've been:
UserImg.Attributes.Add("onmouseover", "javascript:OnHover('" + this.imageHoverTrigger.UniqueID + "','" + this.hiddenLbl.ClientID + "')");
UserImg.Attributes.Add("onmouseout", "javascript:ClearTimer()");
and the javascript function should've been:
var hoverTimer;
// Called on the hover of the user image
function OnHover(trigger, hiddenTxt) {
var field = document.getElementById(hiddenTxt);
// Only post if this hover hasn't been done before
if (field == null || field.innerHTML == "false") {
hoverTimer = setTimeout(function() { ShowInfo(trigger) }, 500);
}
}
// Clears timeout onmouseout
function ClearTimer() {
clearTimeout(hoverTimer);
}
// Retrieves user info from server
function ShowInfo(trigger) {
__doPostBack(trigger, '');
}
I also added a hidden field on the form in order to know when the hover has been executed. The code behind sets the hidden field to true and my javascript checks for the value of the hidden field each time it executes. This stops the code from doing round trips each time the user hovers over the image.

Categories