Creating dynamic DIV in asp .net c# - c#

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

Related

How to download an image that a client uploaded in ASP.NET?

I have a website where users can upload images (part of some report) and I kinda don't know how to save those images.
I think the best way right now is to download those images into a folder of images.
I never really did something like that and everything I tried isn't working.
Here's my code and markup.
HTML markup: the web
<div class="form-group">
<label asp-for="photoPath" class="control-label"></label>
<input asp-for="photoPath" class="" type="file" onchange="readURL(this);" id="file" accept="image/*" multiple />
<span asp-validation-for="photoPath" class="text-danger"></span>
</div>
<div class="form-group" id="display_image" style="display: none; overflow-y: scroll; height: 400px; width: auto;">
<output id="result" style="overflow-y:scroll; height:400px; width:auto; "></output>
<script>
document.querySelector("#file").addEventListener("change", (e) => {
if (window.File && window.FileReader && window.FileList && window.Blob) {
const files = e.target.files;
const output = document.querySelector("#result");
output.innerHTML = "";
for (let i = 0; i < files.length; i++) {
if (!files[i].type.match("image")) continue;
const picReader = new FileReader();
picReader.addEventListener("load", function (event) {
const picFile = event.target;
console.log(picFile.width)
const div = document.createElement("div");
div.innerHTML = `<img class="form-control" id="thumbnail" src="${picFile.result}" title="${picFile.name}" style="height: 500%;width: 200%;"/>`;
output.appendChild(div);
});
picReader.readAsDataURL(files[i]);
document.getElementById('display_image').setAttribute("style", "display:inline;width:auto");
}
} else {
alert("Your browser does not support File API");
}
});
</script>
C# : model class
public class ReportModel
{
/*
Web stuff
*/
[DisplayName("Add photo")]
public List<string> photoPath { get; set; }
/*
More web stuff
*/
}
Well, we need more details as to how and where you plan to save the files.
Assuming a webforms app?
Then probably better to start using asp.net controls. They work MUCH better with your code behind.
So, say this simple markup:
<div id="MyUpLoadArea" runat="server">
<asp:FileUpload ID="FileUpLoad1" runat="server" onchange="ShowImagePreview(this);"
AllowMultiple="True" accept="image/*" style="float:left" />
<asp:Image ID="ImgPrv" Width="160px" runat="server" style="float:left"/>
<div style="clear:both;height:20px"></div>
<asp:Button ID="cmdUpLoad" runat="server" Text="Up-Load" CssClass="btn" OnClick="cmdUpLoad_Click" />
<script>
function ShowImagePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#<%=ImgPrv.ClientID%>').prop('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</div>
So, when we select say 4 files, it displays the first one, and we have this:
So, in above, we have a standard asp.net button we have to click to up-load the files.
The code for that can say be this:
protected void cmdUpLoad_Click(object sender, EventArgs e)
{
string strSQL = "";
SqlCommand cmdSQL;
foreach (HttpPostedFile OneFile in FileUpLoad1.PostedFiles)
{
string strSaveFile = Server.MapPath("~/UpLoadFiles/");
strSaveFile += OneFile.FileName;
OneFile.SaveAs(strSaveFile);
// now add this row to data base
strSQL = "INSERT INTO MyUpLoadFiles (FileName, Size, UpLoadTime, User_ID, SavePath) " +
"VALUES (#FileName, #Size, #UpLoadTime, #User_ID, #SavePath)";
cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#FileName", SqlDbType.NVarChar).Value = OneFile.FileName;
cmdSQL.Parameters.Add("#Size", SqlDbType.Int).Value = OneFile.ContentLength;
cmdSQL.Parameters.Add("#UpLoadTime", SqlDbType.DateTime).Value = DateTime.Now;
cmdSQL.Parameters.Add("#User_ID", SqlDbType.Int).Value = Session["User_ID"];
cmdSQL.Parameters.Add("#SavePath", SqlDbType.NVarChar).Value = "~/UpLoadFiles/" + OneFile.FileName;
General.MyRstE(cmdSQL);
}
// ALL files saved, display the grid of up-loaded files
strSQL = #"SELECT * FROM MyUpLoadFiles
WHERE User_ID = " + Session["User_ID"].ToString() +
" ORDER BY UpLoadTime DESC ";
cmdSQL = new SqlCommand(strSQL);
DataTable rstFiles = General.MyRstP(cmdSQL);
GridView1.DataSource = rstFiles;
GridView1.DataBind();
MyUpLoadArea.Style.Add("display", "none"); // hide up-load area
MyFileView.Style.Add("display", "normal"); // show file grid
}
so, we send/save all files to the folder MyUpLoadFiles.
We save each file into a database - so we can list them out later, and show ONLY the one users file(s).
So, right below the above div and markup, I have a gridview, like this:
<div id="MyFileView" runat="server">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns = "False" ShowHeaderWhenEmpty="true" CssClass="table"
width="50%" >
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:BoundField DataField="UpLoadTime" HeaderText="UpLoaded" />
<asp:TemplateField HeaderText="Preview" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" width="120px"
ImageUrl = '<% # Eval("SavePath") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" CssClass="btn" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
So, now when I hit up-load button, I get/see this:
We of course need to wire up a event for the download button.
Say, this:
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" CssClass="btn"
OnClick="cmdDownLoad_Click" />
And that code could be:
protected void cmdDownLoad_Click(object sender, EventArgs e)
{
Button myBut = sender as Button;
GridViewRow gRow = myBut.NamingContainer as GridViewRow;
string strFileOnly = gRow.Cells[0].Text;
string strFile = "";
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
string sMineType = MimeMapping.GetMimeMapping(strFileOnly);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileOnly);
Response.TransmitFile(strFile);
Response.End();
}
I also have two helper routines MyRstP and MyRstE - they are just some general code routines I have (became VERY tired of typing code over and over to get a simple conneciton string setup, and then execute some code to return a table, or to execute some sql code. So, those two routines were this:
public static DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
public static void MyRstE(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
Not really much important - but the above two routines are handy, and thus I don't type that code over and over for simple and general data operations.

click event inside a click event is not firing

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.

How to extract information from database?

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 ";
}
}
}

The name '' does not exist in the current context - Sporadic

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

Clicking HyperLink causes Update Panel to perform Full PostBack?

Update panel does a full post back when I am just trying to do a partial post back. I just want to be able to update the Repeater and not update the whole page when i click the hyperlinks previous page and next page .
protected void Page_Load(object sender, EventArgs e)
{
PagedDataSource objpd = new PagedDataSource();
string connStr = ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString;
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
SqlCommand mySqlSelect = new SqlCommand("SELECT * FROM [Comments]", mySQLconnection);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataTable table = new DataTable();
mySqlAdapter.Fill(table);
objpd.DataSource = table.DefaultView;
objpd.AllowPaging = true;
objpd.PageSize = 1;
int currentPage;
if (Request.QueryString["page"] != null)
{
currentPage = Int32.Parse(Request.QueryString["page"]);
}
else
{
currentPage = 1;
}
objpd.CurrentPageIndex = currentPage - 1;
// Label1.Text = "Page " + currentPage + " of " + pds.PageCount;
if (!objpd.IsFirstPage)
{
linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
}
if (!objpd.IsLastPage)
{
linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
}
Repeater1.DataSource = objpd;
Repeater1.DataBind();
}
This is my HTML
<div class="comment">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table class="commentsx" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="name">
<div class="right">
<%# Eval("CommentUserName") %>
</div>
<div class="left">
<%# Eval("CommentDateTime") %>
</div>
</td>
</tr>
<tr>
<td>
<div class="mess">
<%# Eval("CommentMessage") %>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:HyperLink ID="linkPrev" runat="server">Previous Page</asp:HyperLink>
<asp:HyperLink ID="linkNext" runat="server">Next Page</asp:HyperLink>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="DataBinding" />
</Triggers>
</asp:UpdatePanel>
</div>
Hyperlink controls don't do a postback at all, they evaluate to regular links that will do a GET, not a POST.
Since it seems you want something that looks like a link, but does a postback rather than a GET, what you need is a LinkButton. It looks like a link, but acts like a button and performs a postback.
Figure I would post an answer to my own question since I figure it out with help of Servy. Hyperlinks do a Get not a post that is why my previous code above was not working. So I rework my code to include the following.
I added Two buttons
Made Event Handlers for the Two buttons to create a POST
Here is my Code might help someone
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default to showing the first page
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
private void updateMessage()
{
PagedDataSource objpd = new PagedDataSource();
string connStr = ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString;
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
SqlCommand mySqlSelect = new SqlCommand("SELECT * FROM [Comments]", mySQLconnection);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataTable table = new DataTable();
mySqlAdapter.Fill(table);
objpd.DataSource = table.DefaultView;
objpd.AllowPaging = true;
objpd.PageSize = 1;
objpd.CurrentPageIndex = CurrentPage;
//disable pre or next buttons if necessary
cmdPrev.Enabled = !objpd.IsFirstPage;
cmdNext.Enabled = !objpd.IsLastPage;
Repeater1.DataSource = objpd;
Repeater1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
updateMessage();
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
updateMessage();
}
protected void cmdNext_Click(object sender, EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
updateMessage();
}
here is my html
<div class="comment">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table class="commentsx" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="name">
<div class="right">
<%# Eval("CommentUserName") %>
</div>
<div class="left">
<%# Eval("CommentDateTime") %>
</div>
</td>
</tr>
<tr>
<td>
<div class="mess">
<%# Eval("CommentMessage") %>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:button id="cmdPrev" runat="server" text=" << " onclick="cmdPrev_Click"></asp:button>
<asp:button id="cmdNext" runat="server" text=" >> " onclick="cmdNext_Click"></asp:button></td>
</ContentTemplate>
</asp:UpdatePanel>
</div>

Categories