I am trying to create a Login page and validating the incoming details against the database. But my code isn't able to cross check data from the database. Below is the output result I'm getting from the application:
Output
Following is the code I'm working on
Default.aspx Code:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"AutoEventWireup="true" CodeFile="LogIn.aspx.cs" Inherits="LogIn" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<!-- Login & Register -->
<section>
<div class="pageintro">
<div class="pageintro-bg">
<img src="images/bg-page_01.jpg" alt="About Us"/>
</div>
<div class="pageintro-body">
<h1 class="pageintro-title">Login</h1>
<nav class="pageintro-breadcumb">
<ul>
<li>
Home
</li>
<li>
Login
</li>
</ul>
</nav>
</div>
</div>
</section>
<!-- Login -->
<div class="col-lg-6 ">
<div class="au-form-body p-r-lg-15 p-r-xl-15">
<h2 class="au-form-title form-title-border">Login</h2>
<fieldset class="m-t-40">
<div class="form-group au-form require">
<label>Email address</label>
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
</div>
<div class="form-group au-form require">
<label>Password</label>
<asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>
</div>
<div class="form-group au-form">
<asp:Button ID="loginbtn" runat="server" Text="Log In" OnClick="Button1_Click" />
<asp:Label ID="loginmessage" runat="server"></asp:Label>
<asp:Button ID="logoutbtn" runat="server" OnClick="Button2_Click" Text="Log Out" Visible="False" />
<div class="form-forgot w-100 m-t-10">
Lost your password?
</div>
</div>
</fieldset>
</div>
</div>
<!-- End Login -->
Default.aspx.cs Code
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;
public partial class LogIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True; MultipleActiveResultSets=true;");
sqlCon.Open();
Type cstype = this.GetType();
SqlCommand cmd;
SqlDataReader rdr;
String strSql1 = "SELECT * FROM Customers ";
cmd = new SqlCommand(strSql1, sqlCon);
rdr = cmd.ExecuteReader();
while (rdr.Read() == true)
{
if (txtemail.Text == (string)rdr["cEmail"] &&
txtpwd.Text == (string)rdr["cPassword"])
{
Session["sFlag"] = "T"; // sFlag = "T" means user has logged in
Session["sName"] = rdr["Firstname"];
Session["sEmail"] = rdr["cEmail"];
Session["sAddress"] = rdr["cCompanyAddress"];
Session["sEmail"] = rdr["cEmail"];
logoutbtn.Visible = true;
sqlCon.Close();
Response.Redirect("Default.aspx");
} //end of if
} //end of while loop
// userid and password not matched, hence login unsuccessful
Session["sFlag"] = "F";
Session["sName"] = "";
Session["sUserId"] = "";
loginmessage.Text = "Error in login - Please login again ";
sqlCon.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
logoutbtn.Visible = false;
Session["sFlag"] = "L"; // L for logout
Session["sName"] = "";
Session["sUserId"] = "";
Session["sOrderNo"] = "";
txtemail.Text = "";
txtpwd.Text = "";
Response.Redirect("Default.aspx");
}
}
Would someone point out what's wrong with the code?
No need to fetch all the records from the database just to check a single result. Change your Button1_Click event code to this:
protected void Button1_Click(object sender, EventArgs e)
{
string username = txtemail.Text;
string password = txtpwd.Text;
using (SqlConnection sqlCon = new SqlConnection(#"Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True; MultipleActiveResultSets=true;"))
{
string query = "SELECT Top(1) * FROM Customers WHERE cEmail = #Username and cPassword = #Password";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.Parameters.AddWithValue("#Username", username);
cmd.Parameters.AddWithValue("#Password", password);
sqlCon.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
Session["sFlag"] = "T"; // sFlag = "T" means user has logged in
Session["sName"] = rdr["Firstname"];
Session["sEmail"] = rdr["cEmail"];
Session["sAddress"] = rdr["cCompanyAddress"];
Session["sEmail"] = rdr["cEmail"];
logoutbtn.Visible = true;
sqlCon.Close();
Response.Redirect("Default.aspx");
}
else
{
Session["sFlag"] = "F";
Session["sName"] = "";
Session["sUserId"] = "";
loginmessage.Text = "Error in login - Please login again ";
}
}
}
Related
the problem is that I have created a click event of link button category_Click and inside this click event I have created multiple dynamic controls and I created a click event of an image button Image_Click and now the issue is that the Category_Click event is firing but the Image_Click event is not firing. please help me.
aspx page code:-
<%# Page Title="" Language="C#" MasterPageFile="~/Homepage.Master" AutoEventWireup="true" CodeBehind="Categories.aspx.cs" Inherits="WebApplication1.Categories" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link rel="Stylesheet" href="Genre.css" />
<link rel="Stylesheet" href="genre_content.css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="categories" runat="server">
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="main" runat="server">
<asp:Panel ID="Panel1" runat="server">
<h2><asp:Label ID="Label1" class="h2" runat ="server" ></asp:Label></h2><br/>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server">
<div class="data">
<div class="image">
<asp:Image ID="Image1" runat="server" Cssclass="Img" />
</div>
<div class="description">
<asp:Label ID="Name" runat="server" class="name"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="(Paperback)"></asp:Label>
<div class="cos-shipping">
<div class="cos">
Rs.<asp:Label ID="cost" runat="server" CssClass="co" ></asp:Label>
</div>
<div class="shipping">
<p>Available</p>
<p>Ships within <b>4-6 Business Days</b></p>
<p>Rs.39 shipping in India per item and low cost Worldwide.</p>
</div>
</div>
<asp:Button ID="Button1" runat="server" Text="Buy Now" class="atc"/>
</div>
</div>
<div class="details">
<h2>Book Details</h2>
<asp:Label ID="about" runat="server" CssClass="about" ></asp:Label>
<p>Author: <asp:Label ID="author" runat="server" ></asp:Label> </p>
<p>ISBN: <asp:Label ID="isbn" runat="server" ></asp:Label> </p>
<p>Pubisher: <asp:Label ID="publisher" runat="server" ></asp:Label> </p>
<p>No of pages: <asp:Label ID="nop" runat="server" ></asp:Label> </p>
<p>Language: <asp:Label ID="language" runat="server" ></asp:Label> </p>
<p>Weight: <asp:Label ID="weight" runat="server" ></asp:Label> </p>
<p>Available For :<asp:Label ID="available" runat="server" ></asp:Label> </p>
</div>
</asp:Panel>
</asp:Content>
aspx.cs page code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class Categories : System.Web.UI.Page
{
private string ide, SQL, SQL2, label;
private int num, i, num2, j;
private ImageButton image;
private LinkButton bookname;
private Label money;
private Label id;
private Button wishlist;
private LinkButton category;
private static DataSet ds, ds2;
private static SqlDataAdapter da, da2;
private static HtmlGenericControl Book;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
Panel3.Visible = false;
con2.Open();
SQL2 = "Select distinct Book_category from Book_List";
da2 = new SqlDataAdapter(SQL2, con2);
ds2 = new DataSet();
DataTable dt2 = new DataTable();
da2.Fill(ds2);
num2 = ds2.Tables[0].Rows.Count;
HtmlGenericControl header = new HtmlGenericControl("div");
header.Attributes.Add("class", "header");
Panel2.Controls.Add(header);
for (j = 0; j < num2; j++)
{
category = new LinkButton();
category.Text = ds2.Tables[0].Rows[j]["Book_category"].ToString();
category.Attributes.Add("runat", "server");
category.Attributes.Add("CausesValidation", "false");
category.Click += new EventHandler(Category_Click);
header.Controls.Add(category);
}
}
protected void Category_Click(object sender, EventArgs e)
{
label = ((LinkButton)sender).Text;
Label1.Text = label;
con.Open();
SQL = "Select * from Book_List where Book_category='" + label + "'";
da = new SqlDataAdapter(SQL, con);
ds = new DataSet();
da.Fill(ds);
num = ds.Tables[0].Rows.Count;
//creating div element and putting all the elements ina div called books
Book = new HtmlGenericControl("div");
Book.Attributes.Add("class", "books");
Panel1.Controls.Add(Book);
for (i = 0; i < num; i++)
{
//creating div element
HtmlGenericControl myDiv = new HtmlGenericControl("div");
myDiv.Attributes.Add("class", "myDiv");
//creating image button
image = new ImageButton();
image.ImageUrl = ds.Tables[0].Rows[i]["Book_image"].ToString();
image.CssClass = "Img";
image.Attributes.Add("runat", "server");
//image.UseSubmitBehaviour = false;
image.Attributes.Add("CausesValidation", "false");
//image.Attributes.Add("OnClick", "image_Click");
//image.OnClientClick = Panel3;
image.Click += new ImageClickEventHandler(Image_Click);
//creating div inside myDiv
HtmlGenericControl content = new HtmlGenericControl("div");
content.Attributes.Add("class", "content");
//creating a label to display id
id = new Label();
id.CssClass = "id";
id.Text = ds.Tables[0].Rows[i]["Book_id"].ToString();
id.Attributes.Add("runat", "server");
//id.Click += new ImageClickEventHandler(id_Click);
//creating a label for displaying name of the book
bookname = new LinkButton();
bookname.CssClass = "name";
bookname.Text = ds.Tables[0].Rows[i]["Book_name"].ToString();
bookname.Attributes.Add("runat", "server");
//bookname.Click += new EventHandler(bookname_Click);
//creating a label for displaying cost of the book
money = new Label();
money.CssClass = "cost";
money.Text = "<br/> Rs " + ds.Tables[0].Rows[i]["Book_cost"].ToString();
money.Attributes.Add("runat", "server");
//creating a button to add the book to the wishlist
wishlist = new Button();
wishlist.Attributes.Add("runat", "server");
wishlist.CssClass = "wishlist";
wishlist.Text = "ADD TO WISHLIST";
Book.Controls.Add(myDiv);
myDiv.Controls.Add(image);
myDiv.Controls.Add(content);
content.Controls.Add(id);
content.Controls.Add(bookname);
content.Controls.Add(money);
content.Controls.Add(wishlist);
}
}
protected void Image_Click(object sender, ImageClickEventArgs e)
{
Panel3.Visible = true;
Panel2.Visible = false;
//ImageButton image = sender as ImageButton;
//Response.Redirect("genre_content.aspx");
ide = ((ImageButton)sender).ImageUrl;
for (i = 0; i < num; i++)
{
if (ide == ds.Tables[0].Rows[i]["Book_image"].ToString())
{
Session["name"] = ds.Tables[0].Rows[i]["Book_name"].ToString();
Session["image"] = ds.Tables[0].Rows[i]["Book_image"].ToString();
Session["cost"] = ds.Tables[0].Rows[i]["Book_cost"].ToString();
Session["isbn"] = ds.Tables[0].Rows[i]["Book_isbn_no"].ToString();
Session["weight"] = ds.Tables[0].Rows[i]["Book_weight"].ToString();
Session["author"] = ds.Tables[0].Rows[i]["Book_author"].ToString();
Session["about"] = ds.Tables[0].Rows[i]["Book_about"].ToString();
Session["publisher"] = ds.Tables[0].Rows[i]["Book_publisher"].ToString();
Session["nop"] = ds.Tables[0].Rows[i]["No_of_pages"].ToString();
Session["language"] = ds.Tables[0].Rows[i]["Book_language"].ToString();
Session["available"] = ds.Tables[0].Rows[i]["Available_for"].ToString();
}
}
Image1.ImageUrl = Session["image"].ToString();
Name.Text = Session["name"].ToString();
about.Text = Session["about"].ToString();
cost.Text = Session["cost"].ToString();
author.Text = Session["author"].ToString();
isbn.Text = Session["isbn"].ToString();
publisher.Text = Session["publisher"].ToString();
nop.Text = Session["nop"].ToString();
language.Text = Session["language"].ToString();
weight.Text = Session["weight"].ToString();
available.Text = Session["available"].ToString();
}
}
}
Your problem is that you dynamicly add the button to your form. If the postback then comes back, your page has no idea about the button because it gets created in your page_load.
You should look into using a gridview or simular control for keeping lists.
I'm stuck with a problem where i can't get the values of any control not just textboxes in button click event so here is the scenario, You can skip it and just can look into my button click event
Page product is performing 2 operations
Create
Update
When a user clicks Edit on GridView in updpage It will redirects it to Product Page to update, Same page is performing Create product operation too, So when I receive QueryString value I'll update the product table and when I won't so I just perform Create operation.
Now I'm stuck when there is no QueryString value so textboxes are updating with a new values but when there is, so they don't give me a new value.
Here is my code
On pageLoad Event I'm filling text boxes with there respective values
where there is an update operation
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
}
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Button event code
protected void btn_Insert_Click(object sender, EventArgs e)
{
getpicture();
SqlCommand cmd;
string pathimage ="";
if (pathimage == "")
{
pathimage = product_image.ImageUrl;
}
else
{
pathimage = ViewState["pathimage"].ToString();
}
if (Request.QueryString["update"] != null)
{
int id = int.Parse(Request.QueryString["update"]);
string query = "UPDATE Products SET product_name=#PRODUCTNAME,price=#PRIZE,unit=#UNIT,product_image=#IMAGE,available=#AVAILABLE,product_category=#CATEGORY,product_brand=#BRAND,product_achv=#ACHIV WHERE id = #ID";
cmd = new SqlCommand(query);
txt_name.Text = "";
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
cmd.Parameters.Add("#ID", id);
param.InsertUpdateData(cmd);
}
else
{
string query = "INSERT INTO Products(product_name,price,unit,product_image,available,product_category,product_brand,product_achv) VALUES(#PRODUCTNAME,#PRIZE,#UNIT,#IMAGE,#AVAILABLE,#CATEGORY,#BRAND,#ACHIV)";
cmd = new SqlCommand(query);
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
param.InsertUpdateData(cmd);
}
}
It is getpicture function used in btn_submit
private void getpicture()
{
try
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string root = Server.MapPath("~");
string path = root + "assets\\images\\products\\";
FileUpload1.SaveAs(path + FileName);
ViewState["pathimage"] = "/assets/images/products/" + FileName;
this.product_image.ImageUrl = "../assets/images/products/upload.png";
}
else
{
Response.Write("Select an Image");
}
}
catch (Exception ex)
{
Response.Write("Select an Image");
}
}
Providing Data access layer Insert Update Data code too
public Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["OnlineStoreConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
System.Web.HttpContext.Current.Response.Write("Succed");
return true;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.ToString());
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Server Controls
<div class="row">
<div class="col-md-6">
<asp:TextBox ID="txt_name" runat="server" CssClass="form-control" placeholder="Product Name"></asp:TextBox>
<br />
<asp:TextBox ID="txt_price" runat="server" CssClass="form-control" placeholder="Product Price"></asp:TextBox>
<br />
<asp:TextBox ID="txt_unit" runat="server" CssClass="form-control" placeholder="Product Unit"></asp:TextBox>
<br />
<asp:DropDownList ID="dd_available" runat="server" CssClass="form-control">
<asp:ListItem>Is Product Available</asp:ListItem>
<asp:ListItem>Available</asp:ListItem>
<asp:ListItem>Not Avaliable</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="dd_category" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_brand" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_achievment" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
</div>
<div class="col-md-2"></div>
<div class="col-md-4">
<asp:Image ID="product_image" runat="server" style="height:231px;width:225px;" CssClass="form-control" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange = "show_image(this);" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3 col-md-offset-6">
<asp:Button ID="btn_Insert" runat="server" Text="Create Product" CssClass="btn btn-primary btn-lg" OnClick="btn_Insert_Click" />
</div>
</div>
Before Clicking update button
Before clicking update button
After I updated text box values respectively and when click button Upload None of my server control value changes. Here it is
Watching local variable
But in case of Creating Product it works
Saad, i think the error is in the page_load event. If in your querystring the update param is not null, then you are always replacing the textboxes with the data of your DB.
Your code should be like this
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Hope it helps...
so i was doing this cascading dropdownlist control to get state,when country dropdown is changed and similarly ,get city on state change..so i was getting whole page refreshed ..so i tried update panel but only state was getting populated on country change but i was not able to change city for some reason..in current code now on state change i have kept city change ,but i want all dropdown to work in update panel i.e on selection of country ,state should be populated and on selection of state ,city should be populated..i am attaching the code
<div class="row">
<div class="medium-6 columns">
<div class="input-single valid">
<asp:DropDownList ID="ddlCountry" runat="server" TabIndex="13" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
<small class="error">Country is required.</small>
</div>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="medium-6 columns">
<div id="countrySubdivisionDiv" class="input-single">
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlState_SelectedIndexChanged"></asp:DropDownList>
<small class="error">Region/State/Province is required.
</small>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="row">
<div class="medium-6 columns">
<div class="input-single">
<asp:UpdatePanel ID="fdf" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCity" runat="server" maxlength="50"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
<small class="error">City is required.</small>
</div>
</div>
<div class="medium-6 columns">
<div class="input-single">
<asp:TextBox ID="txtPostalCode" runat="server" placeholder="Post Code" MaxLength="15" TabIndex="16"></asp:TextBox>
<small class="error">Postcode is required.</small>
</div>
</div>
</div>
</div>
The cs file for the same is.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateContinentsDropDownList();
}
lblCheckEmail.Visible = false;
}
private void PopulateContinentsDropDownList()
{
DataSet ds = Data.spGetCountries();
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "Country_Id";
ddlCountry.DataBind();
ListItem liCountry = new ListItem("Select Country");
ddlCountry.Items.Insert(0, liCountry);
ListItem liState = new ListItem("Select State");
ddlState.Items.Insert(0, liState);
ListItem liCity = new ListItem("Select City");
ddlCity.Items.Insert(0, liCity);
ListItem liCountryCode = new ListItem("Country Code");
ddlCountrycode.Items.Insert(0, liCountryCode);
ddlState.Enabled = false;
ddlCity.Enabled = false;
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedValue == "")
{
ddlState.SelectedIndex = 0;
ddlCity.SelectedIndex = 0;
ddlState.Enabled = false;
ddlCity.Enabled = false;
ddlCountrycode.SelectedIndex = 0;
ddlCountrycode.Enabled = false;
}
else
{
ddlState.Enabled = true;
DataSet ds = Data.spGetStateByCountryId(Convert.ToInt32(ddlCountry.SelectedValue));
ddlState.DataSource = ds;
ddlState.DataTextField = "StateName";
ddlState.DataValueField = "State_Id";
ddlState.DataBind();
DataSet ds1 = Data.spGetCountrycode(Convert.ToInt32(ddlCountry.SelectedValue));
ddlCountrycode.DataSource = ds1;
ddlCountrycode.DataTextField = "CountryCode";
ddlCountrycode.DataValueField = "Country_Id";
ddlCountrycode.DataBind();
//ddlCity.SelectedIndex = 0;
//ddlCity.Enabled = false;
}
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlState.SelectedValue == "")
{
ddlCity.SelectedIndex = 0;
ddlCity.Enabled = false;
}
else
{
ddlCity.Enabled = true;
DataSet ds = Data.spGetCityByStateId(Convert.ToInt32(ddlState.SelectedValue));
ddlCity.DataSource = ds;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "City_Id";
ddlCity.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
DataSet ds = Data.spCheckEmail(txtEmail.Text);
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows[0]["Email_Id"].ToString() == txtEmail.Text)
{
lblCheckEmail.Visible = true;
lblCheckEmail.Text = "Email id already exists , please enter another email id.";
}
else
{
lblCheckEmail.Text = "";
lblCheckEmail.Visible = false;
}
}
else
{
Data objpro = new Data();
string a = ddlYear.SelectedValue;
string b = ddlMonth.SelectedValue;
string c = ddlDate.SelectedValue;
string DateofBirth = ddlDate.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue;
objpro.DOB = DateofBirth;
objpro.Email_Id = txtEmail.Text;
objpro.Password = txtPassword.Text;
objpro.Acc_Currency = ddlCurrency.SelectedValue;
objpro.FirstName = txtFirstName.Text;
objpro.LastName = txtLastName.Text;
objpro.Gender = ddlGender.SelectedValue;
objpro.Address1 = txtAddress1.Text;
objpro.Address2 = txtAddress2.Text;
objpro.Country = ddlCountry.SelectedItem.Text;
objpro.Region_State = ddlState.SelectedItem.Text;
objpro.City = ddlCity.SelectedItem.Text;
objpro.PostalCode = txtPostalCode.Text;
objpro.Phone_Extension = ddlCountrycode.SelectedValue;
objpro.PhoneNo = txtPhoneno.Text;
if (Request.QueryString["Account_Id"] != null)
{
ID = Request.QueryString["Account_Id"];
}
else
{
ID = "0";
}
objpro.Account_Id = Convert.ToInt32(ID);
int k = Data.CustomerInsert(objpro);
Random randno = new Random();
int cc = randno.Next(000000, 999999);
string Uniqueid = "U" + cc;
if (k != -1)
{
Data.spStoreUniqueId(k, Uniqueid);
}
Session["UniqueId"] = Uniqueid;
Session["Email"] = txtEmail.Text;
Page.ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data Saved Successfully');window.location='JoininForm.aspx';", true);
Response.Redirect("Welcome.aspx");
}
}
protected void txtEmail_TextChanged(object sender, EventArgs e)
{
DataSet ds = Data.spCheckEmail(txtEmail.Text);
if (ds.Tables[0].Rows.Count > 0)
{
if (ds.Tables[0].Rows[0]["Email_Id"].ToString() == txtEmail.Text)
{
lblCheckEmail.Visible = true;
lblCheckEmail.Text = "Email id already exists , please enter another email id.";
}
}
}
also attaching the image for same.
Image containing the screen shot of country city and state
Thanking You guys for support
try below code. replace your update panel with below update panel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="medium-6 columns">
<div id="countrySubdivisionDiv" class="input-single">
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlState_SelectedIndexChanged"></asp:DropDownList>
<small class="error">Region/State/Province is required.
</small>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlCountry" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="fdf" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCity" runat="server" maxlength="50"> </asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlState" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
I am creating DIVs dynamically which will fetch data from my sql table(from each row) and will show it in DIVs. What problem I am facing is, it only shows the last row of my sql table in a div form
Here is the html
<div ID = "containerDiv" class="container" runat = "server">
<div ID = "columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID = "textDiv" class="text" runat="server">
</div>
</div>
</div>
and here is the cs code
static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblProducts"))
{
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
columnDiv.ID = "columnDiv" + count;
textDiv.ID = "textDiv" + count;
string name = rdr["prod_name"].ToString();
string price = rdr["prod_price"].ToString();
textDiv.InnerHtml = name + " " + price;
columnDiv.Controls.Add(textDiv);
containerDiv.Controls.Add(columnDiv);
count++;
}
}
}
}
Try using a Repeater, like this (here's the MSDN):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div ID="containerDiv" class="container" runat = "server">
<div ID="columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID="textDiv" class="text" runat="server">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And supply a DataSource in the code behind on the server, and add '<%# Eval("ColumnName") %>' expressions in the markup where appropriate.
The standard approach is to use a GridView:
https://msdn.microsoft.com/en-us/library/aa479342.aspx
I know this is a fairly common error, however the circumstances for me in this case are a little different.
Sometimes, I will not get this error, other times I will, which is not ideal.
Usually I change the inherit name and change the public partial class to the same and it works fine, but after a while I will receive the following.
Error 1 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 31 13 Branch(3)
Error 2 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 32 13 Branch(3)
Error 3 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 33 13 Branch(3)
Error 4 The name 'add_modules' does not exist in the current context all-modules.aspx.cs 34 13 Branch(3)
Error 5 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 42 13 Branch(3)
Error 6 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 43 13 Branch(3)
Error 7 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 44 13 Branch(3)
Below is my C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
public partial class all_modules: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
//Only allow admins, academic program managers and Senior University Managers to view page
helper.Authorised(1, 2, 3);
//get role_id of logged in user
int role_id;
role_id = Convert.ToInt32(Session["role_id"]);
//get id of logged in user
string user_id = Session["user_id"].ToString();
//if admin
if (role_id == 1 || role_id == 3) {
string query = "SELECT courses.course_name, staff_records.f_name, staff_records.l_name, modules.module_name, modules.module_tutor, modules.module_id FROM courses_vs_modules INNER JOIN modules ON courses_vs_modules.module_id = modules.module_id INNER JOIN staff_records ON modules.module_tutor = staff_records.user_id INNER JOIN courses ON courses_vs_modules.course_id = courses.course_id WHERE (courses.school IN (SELECT school_id FROM staff_records AS staff_records_1 WHERE (user_id = #user_id))) ORDER BY courses.course_name";
DataTable dt = GetData(query, user_id);
display_modules.DataSource = dt;
display_modules.DataBind();
display_modules.Visible = true;
add_modules.Visible = true;
}
//if senior uni manager
if (role_id == 2) {
string query = "SELECT courses.course_name, staff_records.f_name, staff_records.l_name, modules.module_name, modules.module_tutor, modules.module_id FROM courses_vs_modules INNER JOIN modules ON courses_vs_modules.module_id = modules.module_id INNER JOIN staff_records ON modules.module_tutor = staff_records.user_id INNER JOIN courses ON courses_vs_modules.course_id = courses.course_id ORDER BY courses.course_name";
DataTable dt = GetDataSen(query);
display_modules.DataSource = dt;
display_modules.DataBind();
display_modules.Visible = true;
}
}
private static DataTable GetData(string query, string user_id) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
cmd.Parameters.AddWithValue("#user_id", user_id);
sda.Fill(dt);
return dt;
}
private static DataTable GetDataSen(string query) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
And this is my ASP.net
<%# Page Title="All Modules" MasterPageFile="MasterPage.master" Language="C#" AutoEventWireup="true" CodeFile="~/all-modules.aspx.cs" Inherits="all_modules" %>
<asp:Content ContentPlaceHolderID="head" Runat="Server">
<script>
$(document).ready(function () {
//makes contains filter case insensitive
$.expr[":"].contains = $.expr.createPseudo(function (arg) {
return function (elem) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
//search has the user types
$('.search-box').keyup(function () {
var search_term = $(this).val();
if (search_term == "") {
//show all if nothing was entered
$('.project-link').removeClass('hide');
} else {
// hide all and then show only the search results
$('.project-link').addClass('hide');
$('.module-list *:contains("' + search_term + '")').closest('.project-link').removeClass('hide');
}
//check if any results were found
if ($('.project-link').not('.hide').length)
{
$('.no-results').addClass('hide');
} else {
$('.no-results').removeClass('hide');
}
});
});
</script>
</asp:Content>
<asp:Content ContentPlaceHolderID="menu" Runat="Server"></asp:Content>
<asp:Content ContentPlaceHolderID="main_content" Runat="Server">
<div class="row">
<div class="col-12">
<h1>All Modules</h1>
<h5 class="subheading">Search through a complete list of modules.</h5>
Add Modules
</div>
</div>
<div class="row">
<div class="col-12">
<div class="panel">
<h3>Search Modules:</h3>
<input type="text" class="search-box full-width" placeholder="Search via module name, code, course or lecturer" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="panel">
<asp:ListView ID="display_modules" runat="server" Visible="false">
<ItemTemplate>
<div class="project-link module-list">
<a href='<%# "module.aspx?module=" + Eval("module_id") %>'>
<p class="project-label"><%# Eval("course_name") %>
</p>
<asp:Label Text='
<%# Eval("module_id") + " - " %>' runat="server" CssClass="story-title" ID="Label1" />
<asp:Label Text='
<%# Eval("module_name") %>' runat="server" CssClass="story-title" ID="story_titleLabel" />
<span>
<p class="project-label"><%# Eval("f_name") + " " + Eval("l_name") %>
</p>
<div class="to-module"></div>
</a>
</div>
</ItemTemplate>
</asp:ListView>
<p class="hide no-results">No search results were found.</p>
</div>
</div>
</div>
</asp:Content>
Any idea why this might be happening? Any help would be greatly appreciated