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
I am doing a little school project with ASP.NET, and I'm trying to get all products from the Database, show it and have "Add to card" button for every one of them. I managed to do all this, except adding the button. I have a function that gets all the products and I'm binding it with ASP Repeater. The problem is, when I try to add a button, it says that I need to use the form tag first, when I add the form tag it says it needs to have runat="server", but when I add it, it says I can't have more than one runat="server". The Repeater tag is using it also, and I'm stuck. Can anyone suggest something? Thank you!
private void bindPopularProducts()
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Food", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable fFood = new DataTable();
sda.Fill(fFood);
popularFood.DataSource = fFood;
popularFood.DataBind();
}
}
}
}
and this
<asp:Repeater ID="popularFood" runat="server">
<ItemTemplate>
<div class="col-md-4">
<div><%# Eval("name") %></div>
<div><asp:Image ID="foodImage" runat="server" ImageUrl='<%# "~/images/food/" + Eval("image").ToString() %>' Visible="true" CssClass="img-responsive" /></div>
<div>
<div class="col-md-4 text-left"><%# "$"+Eval("price_small")+"/small" %></div>
<div class="col-md-8 text-right">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I'm trying to put the button inside the text-right div
Within your Repeater's ItemTemplate, add a button. In the button, set the CommandArgument to some key value that uniquely identifies the product.
<asp:Button ID="Button1" runat="server" Text="Click Me" CommandArgument='<%# Eval("Product.Key") %>' OnClick="Button1_Click" />
In your code, the event handler can use the button's CommandArgument to get the product key and execute your "Add to card" method.
protected void Button1_Click(object sender, EventArgs e)
{
string myProductKey;
// Use "myProductKey" to do something with the Product record...
myProductKey = ((Button)sender).CommandArgument;
}
I have a textbox and a label in ASP.NET and i want to automatically update the label with a value from database that is fetched using the content entered in textbox. This should be done dynamically when the text is changed in textbox and if a match if found in database, the corresponding value should be displayed in the label field (without page refresh). In this case I will enter employee ID in textbox and employee name should be displayed in label. I am using the following code,
<asp:ScriptManager ID="script_manager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="update_name" runat="server">
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" AutoPostBack="true" OnTextChanged="text_empID_TextChanged" runat="server"></asp:TextBox>
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as follows,
protected void text_empID_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmployeeName from EmployeeTable where EmployeeID=#id", con);
cmd.Parameters.AddWithValue("#id", text_empID.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
label_empName.Text = dt.Rows[0]["EmployeeName"].ToString();
}
}
But this is not working. Also after entering a value in textbox and if i click outside the box, the text inside disappears. Is there any other way to do this? or am i doing something wrong here?
I would suggest that you should add a button because the text_changed event only fires when the text-box blurs (loses focus).
That's a very weird behaviour and most users are not used to it and will not expect it.
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" runat="server></asp:TextBox>
<asp:button id="btnSearch" runat="server" OnClick="text_empID_TextChanged" />
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
In any case, have you added a breakpoint? does the event fire? do you get any data back in the DataTable?
EDIT
After your last comment I am convinced that you are clearing the contents of the label on page load.
please, make sure that you only do that in the following context:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
label_empName.Text = "";
}
}
Firstly, I am using a repeater to display a number of events. I have an Events table and the columns are "EvtName, EvtType, and EvtVote". I am using a repeater to create each event as shown below
<asp:Repeater runat="server" ID="repeaterEvent" DataSourceID="imgCats">
<ItemTemplate>
<div class="jumbotron">
<h2><asp:Label ID="lblEventTest" runat="server" Text='<%#Bind("EvtName") %>'></asp:Label></h2>
<h3><asp:Label ID="Label1" runat="server" Text='<%#Bind("EvtType") %>'></asp:Label></h3>
<h4><asp:Label runat="server">Amount Attending: </asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%#Bind("EvtVote") %>'></asp:Label></h4>
<asp:Button runat="server" ID="eventButton" Text="Attending" class="btn btn-primary" OnClick="EventVote_Click"/>
</div>
</ItemTemplate>
</asp:Repeater>
The code for event button click is:
public void EventVote_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE Events SET EvtVote = EvtVote + 1");
loadDatabase(cmd);
Response.Redirect(Request.Url.AbsoluteUri);
}
and this is updating every single event by 1 instead of just the one clicked on. When the event is being created it is given an ID called eventID so I might need to update my sql query to incorporate that? I'm not too sure how I would do this. Thanks in advance!
On a side-note, I would also like to disable the button for that event clicked once it has been clicked
Si I'm using a repeater item command which is shown below
public void repeaterEvent_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{
// check if the command name is close (if it's the button)
if (e.CommandName == "Vote")
{
SqlCommand cmd = new SqlCommand("UPDATE Events SET EvtVote = EvtVote + 1 WHERE EventID = '" + EventID + "'");
loadDatabase(cmd);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
although it's not updating at all now
Try using the ItemCommand event:
How to get Row value on button Click
ASP.Net Repeater: Get Item, ItemIndex, CommandName and CommandArgument on Click Events
Im using a repeater to display some products in an online shop for a school project. This is how the front end looks with the repeater
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="rptList_ItemCommand">
<ItemTemplate>
<span style="float:left; padding:25px;" class="backgrnd">
<asp:ImageButton ID="imgProd" runat="server" style="width:150px; height:150px;" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "productImg")%>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="ViewIndividProd"/><br />
<p style="clear:left;">
<asp:Label ID="lbName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "productName")%>' /><br />
<asp:Label ID="lbUnitPrice" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "unitPrice")%>'/><br />
<asp:Label ID="lbRatings" runat="server" Text=''>Ratings</asp:Label><br />
<asp:LinkButton ID="linkCart" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="AddToCart">Add to Cart</asp:LinkButton>
</p>
</span>
</ItemTemplate>
</asp:Repeater>
As you can see I've added on the OnItemCommand in the Repeater tag so that this is invoked whenever one of the buttons(image/link) is fired. That works perfectly fine for both commandname AddToCart and ViewIndividProd. However, i want to store the the productid of a specific item that was invoked by the particular button. In my case now, it only stores ONE productid in the arraylist at a time and 'forgets' the productid that was stored previously when another linkbutton is clicked.
Question How do i make it such that everytime a linkbutton in the repeater is fired, it remembers the productid pertaining to the linkbutton that was fired and save these ids into the arraylist?
This is how the back end looks
ArrayList cart = new ArrayList();
protected void rptList_ItemCommand(object sender, RepeaterCommandEventArgs e) {
if (e.CommandName == "ViewIndividProd") {
Session["productID"] = e.CommandArgument.ToString();
Response.Redirect("IndividProduct.aspx");
}
if (e.CommandName == "AddToCart") {
string prodid = e.CommandArgument.ToString();
cart.Add(prodid);
Session["ShoppingCart"] = cart;
Response.Redirect("IndividCat.aspx");
}
msg.Text = "Shopping cart: " + String.Join(",", cart.ToArray());
}
Your feedback would be much appreciated.
You need to understand the Asp.net Page life cycle.
A new instance of your Page object is created on every request.
Values from your input are populated into it.
Your array list is getting recreated every time.
If you want the values to persist, you will have to store your arraylist in the ViewState or the Session
Refer: How to: Save Values in View State
void Page_Load(object sender, EventArgs e)
{
if (ViewState["arrayListInViewState"] != null)
{
PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
}
else
{
// ArrayList isn't in view state, so we need to create it from scratch.
PageArrayList = CreateArray();
}
// Code that uses PageArrayList.
}
We can store comma separated or JSON value in either Session or hidden variable (If you are on the same page and opening new page in different tab then we can use hidden variable also). So every time an button has been click we can append the product id.