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");
Related
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!
**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)
{
}
}
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;
}
}
}
I'm new to c# and I'm trying to build my skills without using any of the wizard tools (eg. login wizard) provided in .net. So far I've been successful in creating a very basic login website.
I'm trying to create a user profile page that will display all the data (first name, last name, etc) of the user logged in.
Text boxes on the page should populate on Page_Load but they are not.
here is the aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UserProfile.aspx.cs" Inherits="TimeHub2.UserProfile" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="UserProfile" runat="server">
<div class="header">
<h1>TimeHub</h1>
<ul>
<li>my cards</li>
<li>profile</li>
<li>help</li>
<li><asp:Label runat="server" ID="userloggedin"></asp:Label></li>
<li><asp:button runat="server" id="buttonLogout" text="Log Out" onClick="logOutClick" /></li>
</ul>
</div>
<div>
<label for="username">username</label>
<asp:TextBox runat="server" id="username"></asp:TextBox>
<label for="first_name">first name</label>
<asp:TextBox runat="server" ID="first_name"></asp:TextBox>
<label for="middle_intial">middle initial</label>
<asp:TextBox runat="server" ID="middle_intial"></asp:TextBox>
<label for="last_name">last name</label>
<asp:TextBox runat="server" ID="last_name"></asp:TextBox>
</div>
<div>
<label for="star">star</label>
<asp:TextBox runat="server" ID="star"></asp:TextBox>
<label for="rank">rank</label>
<asp:TextBox runat="server" ID="rank"></asp:TextBox>
</div>
<div>
<label for="assignment">assignment</label>
<asp:TextBox runat="server" ID="assignment"></asp:TextBox>
<label for="regular_shift">regular shift</label>
<asp:TextBox runat="server" ID="regular_shift"></asp:TextBox>
</div>
<div>
<label for="contact_phone">contact phone</label>
<asp:TextBox runat="server" ID="contact_phone"></asp:TextBox>
<label for="phone_type">phone type</label>
<asp:DropDownList ID="phone_type" runat="server">
<asp:ListItem>home</asp:ListItem>
<asp:ListItem>cell</asp:ListItem>
</asp:DropDownList>
<label for="email">sfpd email</label>
<asp:TextBox runat="server" ID="email" TextMode="Email"></asp:TextBox>
</div>
<div>
<asp:Button runat="server" ID="save" Text="update profile" />
</div>
</form>
</body>
</html>
Here is the c# code I have written to populate the TextBox "first_name":
protected void Page_Load(object sender, EventArgs e)
{
//show user logged in
if (Session["New"] != null)
{
userloggedin.Text = Session["New"].ToString();
}
//else redirect to login
else
Response.Redirect("Login.aspx");
SqlConnection conn = new SqlConnection(Connection-String);
SqlDataReader profileReader = null;
string userDataQuery = "SELECT * FROM dbo.users WHERE username ='" + userloggedin.Text + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(userDataQuery, conn);
profileReader = cmd.ExecuteReader();
while(profileReader.Read())
{
first_name.Text = profileReader["first_name"].ToString();
}
conn.Close();
}
Thanks for your help
solved my own problem. The issue was in the column names of my database. my naming convention used underscores in the column names, however I omitted the underscore for the column in question. Rather than 'first_name' as it should have been, it was 'first name'.
If You are retrieving Only FirstName then There is no need to use *
try like this
string userDataQuery = "SELECT first_name FROM dbo.users
WHERE username ='" + userloggedin.Text + "'";
while(profileReader.Read())
{
first_name.Text = profileReader["first_name"]==DBNull.Value ? "":
profileReader["first_name"].ToString();
}
Beware of SQL Injection Always Use SqlParameter
<asp:Repeater ID="RepCourse" runat="server">
<ItemTemplate>
<div style="width:400px"></div>
<div class="course" style="float: left; margin-left: 100px; margin-top: 100px">
<div class="image">
<asp:Image ID="imgteacher" runat="server" Height="150" Width="248" ImageUrl='<%# "ShowImage.ashx?id="+ DataBinder.Eval(Container.DataItem, "CourseID") %>'/>
</div>
<div style="margin-left: 3px; width: 250px">
<div class="name">
<asp:Label runat="server" ID="lblname" Text='<%#Eval("CourseName") %>'></asp:Label>
</div>
<div style="height: 13px"></div>
<div id="teacher">
<%#Eval("UserName") %>
</div>
</div>
<div style="height: 4px"></div>
<div class="date">
<div id="datebegin">
<asp:Label ID="lbldatebegin" runat="server" Text='<%#Eval("BeginDate") %>'></asp:Label>
</div>
<div id="dateend">
<asp:Label ID="lbldateend" runat="server" Text='<%#Eval("ClosingDate") %>'></asp:Label>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
In my project Repeater Control works fine. And now I need pagination for replacing those data. But I don't have any information about this. May be someone give me advice about this issue.
As shown below picture.
There's no built-in pagination in the Repeater control, but based on this article, you can achieve pagination in the Repeater control by creating another Repeater control for pages and use PagedDataSource as it's source.
First, add this to your markup:
<div style="overflow: hidden;">
<asp:Repeater ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="btnPage"
style="padding:8px;margin:2px;background:#ffa100;border:solid 1px #666;font:8pt tahoma;"
CommandName="Page" CommandArgument="<%# Container.DataItem %>"
runat="server" ForeColor="White" Font-Bold="True">
<%# Container.DataItem %>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
Next, add the following property in your code behind:
//This property will contain the current page number
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set { ViewState["PageNumber"] = value; }
}
Finally add the following methods:
protected void Page_Load(object sender, EventArgs e)
{
BindRepeater();
}
private void BindRepeater()
{
//Do your database connection stuff and get your data
SqlConnection cn = new SqlConnection(yourConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cmd.CommandText = "Select * from YourTable";
//save the result in data table
DataTable dt = new DataTable();
ad.SelectCommand = cmd;
ad.Fill(dt);
//Create the PagedDataSource that will be used in paging
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
//Control page size from here
pgitems.PageSize = 4;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.PageCount > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
}
else
{
rptPaging.Visible = false;
}
//Finally, set the datasource of the repeater
RepCourse.DataSource = pgitems;
RepCourse.DataBind();
}
//This method will fire when clicking on the page no link from the pager repeater
protected void rptPaging_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
BindRepeater();
}
Please give it a try and if you faced any issue just inform me.
Edit: Alternative Solution
Another excellent solution can be found Here, this solution includes the Navigation buttons of pages. You'll need to download files from that link to see a functional pagination and just replace the DataList control with your Repeater control.
Hope this helps.