**ASPX CODE** this is the aspx code
<% for (int i = 0; i < pricePageObj.cartItemsgetset; i++)
{ %>
<div class="row">
<div class="col-md-1 ">
<% Response.Write(i + 1); %>
</div>
<div class="col-md-2 ">
<% Response.Write(svcID[i]); %>
</div>
<div class="col-md-2 ">
<% Response.Write(svcName[i]); %>
</div>
<div class="col-md-3 ">
<% Response.Write(svcDesc[i]); %>
</div>
<div class="col-md-2 ">
<% Response.Write(svcCharges[i]); %>
</div>
<div class="col-md-1 ">
<asp:Button CssClass="btn btn-danger" runat="server" Text="Remove" CommandArgument="dont know how to pass i here" OnCommand="onRemove" />
</div>
</div>
<%} %>
Let's say i=0 ; i<5; i++. so for loop will go for 5 times. so i want to send i as a parameter in the code behind to read the value of i.
C# CODE code behind
public void onRemove(object sender, CommandEventArgs e)
{
try
{
string indexx = Convert.ToString(e.CommandArgument);
System.Diagnostics.Debug.WriteLine("String index = " + indexx);
}
catch (Exception ex)
{
}
}
I want to send that 'i' index in the code behind. Any help?
When i clicked on the button, i want to read that i in the onRemove event.
any help?
Here is how we normally display a collection inside Bootstrap divs in ASP.NET Web Form. If we want to manipulate individual row, we use ItemDataBound event.
It seems a lot of code compare to your original question, but this is a recommended approach in ASP.NET Web Form.
<asp:ListView runat="server" ID="ListView1"
ItemPlaceholderID="ItemPlaceholder"
OnItemDataBound="ListView_ItemDataBound">
<LayoutTemplate>
<asp:Panel runat="server" ID="ItemPlaceholder"></asp:Panel>
<asp:DataPager runat="server" ID="DataPager" PageSize="3">
<Fields>
<asp:NumericPagerField ButtonCount="5" PreviousPageText="<" NextPageText=">" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<div class="row">
<div class="col-md-1">
<%# Eval("Id") %>
</div>
<div class="col-md-2">
<%# Eval("Name") %>
</div>
<div class="col-md-1">
<asp:Button CssClass="btn btn-danger" runat="server" Text="Remove"
CommandArgument='<%# Eval("Id") %>' ID="RemoveButton"
OnCommand="RemoveButton_Command" />
</div>
</div>
</ItemTemplate>
</asp:ListView>
Code Behind
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.DataSource = new List<User>
{
new User {Id = 1, Name = "John"},
new User {Id = 2, Name = "Marry"},
new User {Id = 3, Name = "Nancy"},
new User {Id = 4, Name = "Eric"},
};
ListView1.DataBind();
}
}
protected void RemoveButton_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
}
protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
User user = e.Item.DataItem as User;
}
}
}
<% Response.Write(i + 1); %>
By doing this, you are passing i to the Response.Write method.
You should be able to just write a method in your code behind.
Code behind sample method:
protected int Foo(int bar){
//do something with bar
return bar;
}
You should be able to do this on the .aspx page now:
<% Response.Write(Foo(1) + 1); %>
You can access all of the methods in your code behind by putting the below line at the top of your page, replacing MyCoolPage with your page name. This line should be added for you automagically, though, when you create a web form page:
<%# Page CodeBehind="MyCoolPage.aspx.cs" Inherits="MyCoolPage" Language="C#" %>
Instead of doing what you are doing with your button, just add an OnClick event instead of what you are doing now, as follows:
<asp:Button CssClass="btn btn-danger" runat="server" Text="Remove" OnClick="DoSomethingCool(i) />
DoSomethingCool:
protected void DoSomethingCool(int index){
try
{
System.Diagnostics.Debug.WriteLine("index = " +
index);
}
catch (Exception ex)
{
}
}
Related
I have a repeater inner another repeater and this second one i have a list of checkbox and i need to get the value of the checked.
This is my front code:
<asp:Repeater runat="server" ID="rptPerfis" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="mws-form-row">
<ul class="mws-form-list inline" style="float: none; display: inline;">
<li style="padding-top: 10px;">
<%# rptNome(Container) %></li>
</ul>
<asp:Repeater runat="server" ID="rptUsers">
<ItemTemplate>
<div class="mws-form-item radioPermissoes clearfix" style="float: none;">
<ul class="mws-form-list inline">
<li>
<asp:CheckBox runat="server" Text="<%# rptAdministradorNome(Container) %>" ID="checkUser" CssClass="<%# rptAdministradorPostClass(Container) %>" /></li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<br />
<hr />
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton runat="server" ID="fLnkSalvar" class="mws-ic-16 ic-disk" OnClick="fLnkSalvar_Click">Salvar</asp:LinkButton>
and this is how i fill this repeater:
protected void Page_Load(object sender, EventArgs e)
{
listaAdm = Servicos.AdministradorMySql.ListarEmpresa(denuncia.Empresa).OrderByDescending(x => x.Nome).ToList();
todosPerfis = Servicos.Perfil.ListarTodos().ToList();
rptPerfis.DataSource = todosPerfis.Where(x => x.Ativo).OrderBy(x => x.Nome);
rptPerfis.DataBind();
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
int idPerfil = ((Perfil)args.Item.DataItem).ID;
Repeater childRepeater = (Repeater)args.Item.FindControl("rptUsers");
childRepeater.DataSource = listaAdm.Where(x => x.Perfil > 1 && x.Perfil == idPerfil).ToList();
childRepeater.DataBind();
}
}
protected void fLnkSalvar_Click(object sender, EventArgs e)
{
Administrador usuario = new Administrador();
usuario.Permissoes = new List<string>();
// i need to get this values here to fill this `List<string>` and then save
foreach (var x in usuario.Permissoes)
{
Servicos.Denuncia.InserirUsuarios(denuncia.ID, x);
}
}
I've no idea how can i get this values or if there another easier way without add in the list i think its better
You have to use FindControl on multiple levels. First the correct Item in the parent Repeater, then find the CheckBox in the correct Item of the child Repeater.
var cb = ((Repeater)rptPerfis.Items[i].FindControl("rptUsers")).Items[j].FindControl("checkUser") as CheckBox;
PS you need to wrap the code in Page_Load in an IsPostBack check or you will never retrieve the correct checkbox state in a PostBack.
I'm working on a asp.net project. I've been asked to create a page so site admins could add articles and everyone else could add comments under those articles.
I have 2 separate tables in my db, Articles/Comments. On page load I'm populating all the articles with their own related comments within a panel.
I've also been asked to use an accordion so all comments would display in a collapsible manner!
My problem is that only the first article shows up with collapsible comments under it, and the rest do not!
Here is my aspx page:
<%# Page Title="Ref Notes" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="RefNotes.aspx.cs" Inherits="Root.RefNotes" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:Panel ID="refNotes" CssClass="col-xs-12 data-container" runat="server">
</asp:Panel>
</asp:Content>
aspx.cs code:
public partial class RefNotes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
populateNotes();
Page.Title = "Latest Ref Notes";
}
protected void populateNotes()
{
string tag = "";
if (Request.QueryString["tag"] != null) tag = Request.QueryString["tag"];
int post = 0;
if (Request.QueryString["post"] != null) post = Int32.Parse(Request.QueryString["post"]);
MediaService.Article[] articles = Global.mediaService.GetArticles(1, 1); //gets all articles
for (int i = 0; i < articles.Length; i++)
{
if (post > 0 && articles[i].ID != post) continue;
Root.Controls.Blog.RefNotesPost p = (Root.Controls.Blog.RefNotesPost)LoadControl("~/Controls/Blog/RefNotesPost.ascx");
p.SetData(articles[i]);
refNotes.Controls.Add(p);
Root.Controls.Blog.CommentControl c = (Root.Controls.Blog.CommentControl)LoadControl("~/Controls/Blog/CommentControl.ascx");
c.SetData(articles[i].ID);
refNotes.Controls.Add(c);
}
if (articles.Length == 0)
{
Literal l = new Literal();
l.Text = "<h1>No content currently available.</h1>";
refNotes.Controls.Add(l);
}
}
}
CommentControl.ascx code:
# Control Language="C#" AutoEventWireup="true" CodeBehind="CommentControl.ascx.cs" Inherits="Root.Controls.Blog.CommentControl" %>
<div class="row">
Comments:
<asp:Panel ID="errorPanelID" runat="server" CssClass="loginbox-textbox" Visible="false" Style="margin-top: 20px;">
<div class="alert alert-danger fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-times"></i>
<asp:Label ID="errorMsgID" runat="server"></asp:Label>
</div>
</asp:Panel>
</div>
<div id="dvAccordion" style="width: auto">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<h3>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("user") + " at " + Eval("dateTime") + " says:"%>'></asp:Label></h3>
<div style="background-color: #CFDEE3">
<asp:Literal ID="lit" runat="server" Text='<%#Eval("comment")%>' Mode="Transform" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div>
Add a Comment:<br />
<asp:TextBox ID="txtComment" runat="server" Rows="5" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="saveBtn_Click" Text="Submit " />
<asp:HiddenField runat="server" ID="articleID" Value="0" />
</div>
<script type="text/javascript">
$(function () {
$("#dvAccordion").accordion();
});
</script>
CommentControl.ascx.cs code:
public partial class CommentControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SetData(int artID)
{
Services.Comment[] comments = Global.Tools.GetComments(artID);
articleID.Value = artID.ToString();
if (comments.Length > 0)
{
Repeater1.Visible = true;
Repeater1.DataSource = comments;
Repeater1.DataBind();
}
else
{
Repeater1.Visible = false;
}
}
protected void saveBtn_Click(object src, EventArgs e)
{
AdminService.Employee emp = Global.Tools.GetEmployee(Int32.Parse(Session["eid"].ToString()));
Blog.Comment a = new Blog.Comment();
a.CommentOn = txtComment.Text;
a.CreatedBy = emp.username;
a.DatePosted = DateTime.Now;
a.isVisible = 1;
a.ArticleID = int.Parse(articleID.Value);
if (Request.QueryString["post"] != null)
{
a.ID = Int32.Parse(Request.QueryString["post"]);
}
int result = Global.Tools.CreateComment(a);
if (result <= 0)
{
errorMsgID.Text = "Failed to create comment.";
errorPanelID.Visible = true;
}
else
{
Response.Redirect("/News.aspx");
}
}
txtComment.Text = string.Empty;
}
In the CommentControl.ascx file I had set the accordion based on id (#dvAccordion). I changed it to be based on class (.dvAccordion) and that solved the issue.
So for future references: when you're on a page an "id" can only be called once but a "class" can be called multiple times!
I have 2 files in my web site project, Translator2.aspx and Translator2.aspx.cs. I want to add new class (Erwin:Translator2) to my Translator2.aspx.cs file. However it was error like this :
Severity Code Description Project File Line Suppression State
Error 'translator2_aspx' does not contain a definition for 'Switch'
and no extension method 'Switch' accepting a first argument of type
'translator2_aspx' could be found (are you missing a using directive
or an assembly reference?)
C:\Users\erwin.surya\Documents\Visual
Studio 2017\WebSites\WebSite1\Translator2.aspx 33
Here is my Translator2.aspx code:
<%# Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="Translator2.aspx.cs" MasterPageFile="~/Site.Master" Inherits="Translator2" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="English" CssClass="col-md-2 control-label">English</asp:Label>
<div class="col-md-10">
<asp:TextBox Height="79px" TextMode="MultiLine" Width="452px" runat="server" ID="English" CssClass="form-control" />
</div> </div>
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Submit" Height="39px" Width="100px" Text="Translate" CssClass="btn btn-default" />
</div>
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Switch" Height="39px" Width="100px" Text="Switch" CssClass="btn btn-default" />
</div>
<br /><br /><br />
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="Japanese" CssClass="col-md-2 control-label">Japanese</asp:Label>
<div class="col-md-10">
<asp:TextBox Height="79px" TextMode="MultiLine" Width="452px" runat="server" ID="Japanese" CssClass="form-control" />
</div></div>
<br /><br />
<asp:PlaceHolder runat="server" ID="ErrorMessage" Visible="false">
<p class="text-danger">
<asp:Literal runat="server" ID="FailureText" />
</p>
</asp:PlaceHolder>
</asp:Content>
Here is my Translator2.aspx.cs code:
partial class Translator2 : Page
{
public async void Submit(object sender, EventArgs e)
{
string key = "92fcf1387f844a8";
var authTokenSource = new AzureAuthToken(key.Trim());
string authToken;
try
{
authToken = await authTokenSource.GetAccessTokenAsync();
}
catch (HttpRequestException)
{
if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
return;
}
if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
{
Console.WriteLine("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
return;
}
throw;
}
string output = "";
string text = English.Text;
string uri = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + "en" + "&to=" + "ja";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("Authorization", authToken);
using (WebResponse response = httpWebRequest.GetResponse())
using (Stream stream = response.GetResponseStream())
{
DataContractSerializer dcs = new DataContractSerializer(Type.GetType("System.String"));
string translation = (string)dcs.ReadObject(stream);
Console.WriteLine("Translation for source text '{0}' from {1} to {2} is", text, "en", "ja");
Console.WriteLine(translation);
output = translation;
}
Japanese.Text = output;
}
class Erwin : Translator2
{
string from, to;
public void SwapStrings(string s1, string s2)
{
string temp = s1;
s1 = s2;
s2 = temp;
from = s1;
to = s2;
testing.Text = from;
testing1.Text = to;
}
protected void Switch(object sender, EventArgs e)
{
string str1 = testing.Text;
string str2 = testing1.Text;
System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);
SwapStrings(str1, str2);
}
}
Do you have any idea why I can't add Erwin:Translato2 class? everything works fine before I add the class. Did I miss something?
The Switch method is in a different class than the class that is powering your aspx page. If you want switch to be some kind of utility method, you should create a new class, maybe Erwin in a completely separate file (Erwin.cs), and have a switch method inside that that is public and probably static. I also note that switch doesn't return anything, so not sure what you are trying to accomplish with it.
The OnClick handler for your button should be in the code behind -- ie in the Translator2 class. Inside this handler, you could call Erwin.Switch().
I'am try to make a session on a Textbox in asp.net, that textbox allows the user to enter values from 1-4, but whenever I click on button "book", it gives me an null pointer exception, I am using FindControl function from my c# backend.
Here's my code
.aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="hotels_main.aspx.cs" Inherits="Hotel_Mangement.hotels_main" %>
<asp:Content ID="Content1" ContentPlaceHolderID="hotels_main" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="free website templates, hotel and travel, CSS, XHTML, design layout" />
<meta name="description" content="Hotel and Travel - free website template provided by templatemo.com" />
<link href="/css/templatemo_style.css" rel="stylesheet" type="text/css" />
<div id="templatemo_container">
<!-- Free Website Template by www.TemplateMo.com -->
<div id="templatemo_content">
<div id="content_left" style="background-color:#2C3E50">
<div class="content_left_section">
<div class="content_title_01">Confirm Your Booking</div>
<form id="form1" >
<div class="form_row">
<br /><br />
<big>Check in:</big>
<asp:Calendar ID="checkin" runat="server" OnDayRender="checkin_DayRender" ></asp:Calendar>
<br /><br />
<big>Check out:</big> <asp:Calendar ID="checkout" runat="server" OnDayRender="checkout_DayRender1" ></asp:Calendar>
<br /><br />
<big>Number of room:</big> <asp:TextBox ID="rooms" runat="server" ForeColor="black" placeholder="Number of rooms" type="number" min="1" max="2"></asp:TextBox>
<br /><br />
<big>Number of members per room:</big> <asp:TextBox ID="members" runat="server" ForeColor="black" placeholder="Number of members" type="number" min="1" max="4"></asp:TextBox>
<br /> <br />
<asp:Button ID="book" runat="server" Text="Book" ForeColor="Black" Width="200px" Height="30px" OnClick="book_Click"></asp:Button>
</div>
<div class="cleaner"> </div>
</div> <!-- end of booking -->
<div class="cleaner_h30"> </div>
<div class="cleaner_horizontal_divider_01"> </div>
<div class="cleaner_h30"> </div>
<div class="content_left_section">
<div class="content_title_01">Contact Details</div>
<div class="news_title">Address</div>
<p>The Taj Mahal Palace<br />Apollo Bunder, Near Gateway Of India, Colaba , Mumbai , Maharashtra , India<br />Pincode- 400001</p>
<div class="cleaner_h30"> </div>
<div class="news_title">Phone</div>
<p>022 6665 3366 </p>
<div class="cleaner_h20"> </div>
<div class="news_title">Email Support</div>
<p>reservations#tajhotels.com</p>
</div> <!-- end of news section -->
<div class="cleaner_h30"> </div>
<div class="cleaner_horizontal_divider_01"> </div>
<div class="cleaner_h30"> </div>
<div class="cleaner_h30"> </div>
</div> <!-- end of content left -->
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div id="content_right">
<div class="content_right_section">
<div class="content_title_01">Welcome to The <asp:Label ID="lblhotelname" runat="server" Text='<%#Eval("hotel_name") %>'></asp:Label> </div>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("ImagePath") %>' Height="200px" width="200px"/>
<p><%#Eval("d_desc") %>. </p>
</div>
<div class="cleaner_h40"> </div>
<div class="content_right_2column_box">
<div class="content_title_01">Hotel Facilities</div>
<p> <%#Eval("hotel_facilties") %></p>
</div>
<div class="content_right_2column_box">
<div class="content_title_01">Policies</div>
<ul>
<asp:Label ID="lblpolicies" runat="server" Text='<%#Eval("hotel_policies") %>'></asp:Label>
</ul>
<div class="cleaner_h10"> </div>
</div>
<div class="cleaner_h40"> </div>
<div class="content_right_section">
<div class="content_title_01">Hotel location</div>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("hotel_location") %>'></asp:Label>
<div class="cleaner_h20"> </div>
<div class="cleaner"> </div>
</div>
<div class="content_right_section">
<div class="content_title_01">Hotel price per room</div>
<asp:FormView ID="FormView1" runat="server"></asp:FormView>
<asp:Label ID="lblhotelprice" runat="server" Text='<%#Eval("price")%>'></asp:Label>
<div class="cleaner_h20"> </div>
<div class="cleaner"> </div>
</div>
<div class="cleaner_h20"> </div>
</div> <!-- end of content right -->
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</asp:Content>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace Hotel_Mangement
{
public partial class hotels_main : System.Web.UI.Page
{
int id;
int t1main, t2main, totalmain;
public static List<DateTime> list = new List<DateTime>();
SqlConnection con = new SqlConnection(#"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("hotels.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from hotels_main where hotel_id=" + id + "";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
con.Close();
}
}
protected void checkin_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < DateTime.Now.Date)
{
e.Day.IsSelectable = false;
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Strikeout = true;
}
Session["checkinmain"] = list;
}
protected void checkout_DayRender1(object sender, DayRenderEventArgs e)
{
if ((e.Day.Date < DateTime.Now.Date) || (e.Day.Date < checkin.SelectedDate))
{
e.Day.IsSelectable = false;
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Strikeout = true;
}
Session["checkoutmain"] = list;
}
protected void book_Click(object sender, EventArgs e)
{
if (Session["USER_ID"] == null)
{
Response.Redirect("login.aspx");
}
else
{
TextBox rooms = (TextBox)FindControl("rooms");
Session["roomsmain"] = rooms.Text;
TextBox members = (TextBox)FindControl("members");
Session["membersmain"] = members.Text;
Label lblhotelprice = (Label)FindControl("lblhotelprice");
Session["initialprice"] = lblhotelprice.Text;
t1main = Convert.ToInt32(Session["roomsmain"].ToString());
t2main = Convert.ToInt32(Session["initialprice"].ToString());
totalmain = t1main * t2main;
Session["totalpricemain"] = totalmain;
con.Open();
string insertQuery = "insert into hotel_booking_details(username,hotel_name,hotel_location,check_in,check_out,members,rooms,initial_price,total_price) values('" + Session["USER_ID"].ToString() + "','" + Session["hotel_name"].ToString() + "','" + Session["hotel_location"].ToString() + "','" + Session["checkinmain"].ToString() + "','" + Session["checkoutmain"].ToString() + "','" + Session["membersmain"].ToString() + "','" + Session["roomsmain"].ToString() + "','" + Session["initialprice"].ToString() + "','" + Session["totalpricemain"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(insertQuery, con);
cmd1.ExecuteNonQuery();
con.Close();
Response.Redirect("pay.aspx");
}
}
}
}
First of all, you cannot use another form tag in ASP.Net. You will need to remove <form id="form1" >.
it gives me an null pointer exception, I am using FindControl function
from my c# backend.
TextBox rooms = (TextBox)FindControl("rooms");
About code tries to find rooms textbox inside Page control. rooms control is not a direct child of Page control.
You will need to the find control recursively. Here is the helper method -
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Usage
TextBox rooms = (TextBox)FindControlRecursive(Page, "rooms");
I have an asp.net webform website which stores data in a session and on the 3rd page displays the entries entered on pg1 & pg2.
On the first page the first checkboxes is pre-selected by default but if the user selects/unselects a checkbox, when the user is on the second page, there is a back button but when it's clicked I don't know how to re-show the checkboxes selected/unselected as only the default one is checked.
I'm new to using ASP and session storing so I may be doing something completely wrong. How can I resolve my situation?
My code is:
HTML
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">All services</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02AllServices" runat="server" Checked="True" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">Site content uploading only</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02ContentUploading" runat="server" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">Site content & layout checking</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02ContentLayoutChecking" runat="server" Enabled="False" />
</div>
</div>
Code Behind
protected void Step02SubmitButton_Click(object sender, EventArgs e)
{
Session["Step02AllServices"] = Step02AllServices.Checked;
Session["Step02ContentUploading"] = Step02ContentUploading.Checked;
Session["Step02ContentLayoutChecking"] = Step02ContentLayoutChecking.Checked;
Response.Redirect("/Quotation/pg3.aspx");
}
I know that is needs to be in my Page_Load just not sure how to do it.
The below is what I have for radio buttons and test fields on another page
if (txtData2.Text == string.Empty && Session["pg2"] != null)
{
txtData2.Text = Session["pg2"].ToString();
if (Session["pg2Yes"].ToString() == "Yes")
{
pg2Yes.Checked = Session["pg2Yes"].Equals("Yes");
}
if (Session["pg2No"].ToString() == "No")
{
pg2No.Checked = Session["pg2No"].Equals("No");
}
}
Let's assume that you are on page 3 and you clicked the back button which redirects you to page 2.
On load of page 2, you need to check whether it's a new load (not postback) and if it contains the values on session. If both are true, you need to get the value from session and make the checkbox selected.
So, write the following code in Page2Load
//if you are loading the new page
if (!Page.IsPostBack)
{
if(Session["Step02AllServices"] != null)
{
Step02AllServices.Checked = (bool) Session["Step02AllServices"];
//similarly assign other checkbox values as they are in session already
}
else
{
//do normal assignment
}
}
check the below simple implementation and enhance it according to your requirement and can be done using single page
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="div1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" /><asp:Button ID="Button1" runat="server" Text="Next" OnClick="Button1_Click" />
</div>
<div id="div2" runat="server" visible="false">
<asp:Button ID="Button2" runat="server" Text="Back" OnClick="Button2_Click"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="Next" OnClick="Button3_Click"/>
</div>
<div id="div3" runat="server" visible="false">
<asp:Button ID="Button4" runat="server" Text="Back" OnClick="Button4_Click"/>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
cs code:
using System;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = true;
div3.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
div1.Visible = true;
div2.Visible = false;
div3.Visible = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = false;
div3.Visible = true;
Label1.Text = CheckBox1.Checked.ToString();
Label2.Text = CheckBox2.Checked.ToString();
Label3.Text = TextBox1.Text;
Label4.Text = TextBox2.Text;
}
protected void Button4_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = true;
div3.Visible = false;
}
}
}