I need to know how to display data from a dropdown list. For example:
DropDownList
Select Images
car
boat
fishing
The first thing the user see is the select images dropdown. The user will see some random picture that displays from the select image dropdown.
If the user presses the car picture in the list, and then new picture will show and so on.
Each picture will show up in the html table something like the picture that I have drawn (below). Say each list has three pictures, then each of the three will be displayed in the table (as seen below).
Here is the code I have written so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Collections;
namespace Prototype
{
public partial class HomePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillddlPictuer();
}
}
public void FillddlPictuer()
{
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM pictuer", conn);
try
{
conn.Open();
SqlDataReader readeer = cmd.ExecuteReader();
ListItem newItem = new ListItem();
newItem.Text = "Select Image";
newItem.Value = "0";
ddlMovie.Items.Add(newItem);
while (readeer.Read())
{
newItem = new ListItem();
newItem.Text = readeer["name"].ToString();
newItem.Value = readeer["id"].ToString();
ddlMovie.Items.Add(newItem);
}
StringBuilder sb = new StringBuilder();
}
catch
{
//Handel any error
conn.Close();
}
} //Close the first using
}
}
}
HomePage code
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="HomePage.aspx.cs" Inherits="Prototype.HomePage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderMainSection" runat="server">
<div id="ImageGalleryBorder"></div>
<div id="ChampionBorder"></div>
<div id="OtherStuffBorder">
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolderMainAside" runat="server">
<h1>New videos</h1>
<asp:DropDownList ID="ddlMovie" runat="server"
CssClass="DropDownListAside">
</asp:DropDownList>
<asp:Label ID="lblOutput" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
</asp:Content>
Change the Picture table in SQL to include a path column, this will be used to store the path to the image on the server:
Rename Pictuer table to Picture
ASPX:
<asp:ScriptManager ID="sm" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlMovie" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MovieChanged" />
<asp:PlaceHolder ID="pictures" runat="server" />
<span id="error" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPictures();
AddPicture(ddlMovie.SelectedItem.Value);
ReDisplayPictures();
}
}
private void ReDisplayPictures()
{
List<string> imagePaths = ViewState["Images"] as List<string>;
if (imagePaths != null)
{
foreach (string path in imagePaths)
{
var image = new Image{Width = 100,Height = 100,ImageUrl = path};
pictures.Controls.Add(image);
}
}
}
private void AddPicture(string imageUrl)
{
List<string> imagePaths = ViewState["Images"] as List<string>;
if (imagePaths == null)
imagePaths = new List<string>();
imagePaths.Add(imageUrl);
ViewState["Images"] = imagePaths;
}
protected void MovieChanged(object sender, EventArgs e)
{
AddPicture(ddlMovie.SelectedItem.Value);
ReDisplayPictures();
}
private void GetPictures()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var conn = new SqlConnection(cs))
{
using (var command = new SqlCommand("SELECT * FROM Picture", conn))
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader["name"].ToString();
string path = reader["path"].ToString();
var item = new ListItem { Text = name, Value = path };
ddlMovie.Items.Add(item);
}
}
conn.Close();
}
}
catch (Exception eX)
{
error.InnerHtml = String.Format("An error occured, description - {0}",
eX.Message);
}
}
}
I've created a sample project for you, you can download it here from Google drive (Just click File->Download)
Related
I have a DropDownList that is dynamically populated from SQL Server database.
Currently, the DropDownList has 2 values, 0.20 and 0.30. However, users have informed us that they have several more values to add to the DropDownList.
If one of the users' clients presents water level of 0.20, they receive a discount of $100 or less.
The rest of the DropDownList values must receive $50 or less discount.
I am trying to use a CASE statement that ensures clients with 0.20 receive $100 or less discount and the rest $50 or less discount but I am stuck on how to handle the rest of the DropDownList values.
This is what I have been trying so far and I would like to know if it is possible to use CASE statement to handle this.
protected bool CheckWaterLevel(string wsize, decimal amt)
{
bool valueOK = false;
switch (wsize)
{
case "0.20":
if (amt <= 100)
valueOK = true;
break;
case "0.30":
if (amt <= 50)
valueOK = true;
break;
}
return valueOK;
}
In a nutshell, is it possible to replace case "0.30" with the values of DropDownList with the exception of 0.20?
The DropDownList control ID is ddlWaterLevels
HTML:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<br /><br /><br />
<div>
<asp:Label ID="lblWater" runat="server" Text="Water Size" Width="100px"></asp:Label><br />
<asp:TextBox ID="txt_watersizes" placeholder="Enter new Water Size" Width="150px" runat="server"></asp:TextBox>
<asp:TextBox ID="txt_amount" placeholder="Enter amount" Width="100px" runat="server"></asp:TextBox>
<asp:Button ID="btn_add" runat="server" Text="Add It" onclick="btn_add_Click"
Width="100px" /><br /><br />
<asp:DropDownList ID="ddlWater" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlWater_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" placeholder="Enter new water size" Width="100px" runat="server"></asp:TextBox>
</div>
</asp:Content>
C#:
`using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : Page
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dropbind();
}
}
protected void btn_add_Click(object sender, EventArgs e)
{
ddlWater.Items.Clear();
SqlConnection con = new SqlConnection(conString);
com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = "insert into WaterVolume(WaterSizes,Amount)values(#tsizes,#amount)";
com.Parameters.Clear();
com.Parameters.AddWithValue("#tsizes", txt_watersizes.Text);
com.Parameters.AddWithValue("#amount", txt_amount.Text);
if (con.State == ConnectionState.Closed)
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Write("Records successfully inserted");
clear();
dropbind();
}
private void clear()
{
txt_watersizes.Text = "";
txt_amount.Text = "";
}
private void dropbind()
{
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT WaterSizes FROM WaterVolume", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
ddlWater.DataSource = dt;
ddlWater.DataTextField = "WaterSizes";
ddlWater.DataValueField = "WaterSizes";
ddlWater.DataBind();
ddlWater.Items.Insert(0, new ListItem { Text = "Select", Value = "" });
}
}
}
}
}
private void FetchData()
{
using (SqlConnection con = new SqlConnection(conString))
{
DataTable dt = new DataTable();
con.Open();
String sql = "SELECT Amount FROM WaterVolume WHERE WaterSizes = '" + ddlWater.SelectedItem.Text + "'";
SqlCommand cmd = new SqlCommand(sql, con);
// cmd.Connection.Open();
// cmd.ExecuteNonQuery();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
//If you want to get mutiple data from the database then you need to write a simple looping
TextBox1.Text = dt.Rows[0]["Amount"].ToString();
}
// cmd.Connection.Close();
}
}
protected void ddlWater_SelectedIndexChanged(object sender, EventArgs e)
{
FetchData();
}
}
This is a better solution.
Obviously, I was overthinking it.
As you can see, a user selects water size, a textbox is automatically populated with the corresponding amount.
Since this is an internal app managed by only two people, and per their instruction, if there is a new water size, they don't have to contact us, they just enter the new water size and amount and voila, they are ready to go.
I just need to add some validations to ensure user cannot submit without entering data into the two boxes.
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.
Experts,
Drop-down list is picking data from database and saving against the same column upon opening the web page and save the data, where saving is happening in another instead of same name,
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="form">
<p>
<asp:Label ID="Label1" runat="server" Text="Place Name" AssociatedControlID="txtName"></asp:Label>
<asp:DropDownList ID="txtName" runat="server" >
</asp:DropDownList>
</p>
<p>
<asp:Label ID="Label2" runat="server" Text="Address" AssociatedControlID="txtAddress"></asp:Label>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
</p>
<p>
<asp:HiddenField ID="hdnLocation" runat="server" />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" />
</p>
<p id="message"></p>
</div>
</form>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { $("#message").html("Geolocation is not supported by this browser."); }
function showPosition(position) {
var latlondata = position.coords.latitude + "," + position.coords.longitude;
var latlon = "Latitude" + position.coords.latitude + "," + "Longitude" + position.coords.longitude;
$("#message").html(latlon);
$("[id*=hdnLocation]").val(position.coords.longitude + " " + position.coords.latitude);
}
function showError(error) {
if (error.code == 1) {
$("#message").html("User denied the request for Geolocation.");
}
else if (error.code == 2) {
$("#message").html("Location information is unavailable.");
}
else if (error.code == 3) {
$("#message").html("The request to get user location timed out.");
}
else {
$("#message").html("An unknown error occurred.");
}
}
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Data.Entity.Spatial;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT PlaceID, Name,Address FROM Placeinfo";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Name"].ToString();
txtName.Items.Add(item);
txtName.ClearSelection();
}
}
con.Close();
}
}
}
}
public List<PlaceInfo> GetMyPlaces()
{
return new SampleDBEntities().PlaceInfoes.ToList();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
PlaceInfo placeToEdit = Context.placeinfoes.Find(Convert.ToInt32(txtName.DataValueField));
using (var context = new SampleDBEntities())
{
PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.DataValueField));
placeToUpdate.Name = txtName.Text;
placeToUpdate.Address = txtAddress.Text;
placeToUpdate.Geolocation = DbGeography.FromText("POINT( " + hdnLocation.Value + ")");
context.Entry(placeToUpdate).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
}
}
databaseDATABASE DISPLAY
In order to update an item in a database, we first need to make sure we'll know which one we need to reference.
First, with the creation of your DropDownList, we'll want to hide the ID of the "PlaceInfo" we are displaying. This will create the need for a "SelectMethod", and a few other adjustments:
<asp:DropDownList ID="txtName" runat="server" ItemType="PlaceInfo" DataValueField="PlaceId" DataTextField="Name" SelectMethod="GetMyPlaces"></asp:DropDownList>
The DataTextField property is the one which will display in the actual DropDown, and the DataValueField is a hidden property which we will use to reference the ID so we can call that row later.
The SelectMethod (I have as: GetMyPlaces) is the method we use to populate the DropDownList. Please excuse the brevity, as you can do this a number of ways, but essentially you want to return a list of PlaceInfos:
public List<PlaceInfo> GetMyPlaces()
{
return new SampleDbEntities().PlaceInfoes.ToList();
}
Finally - in the btnSubmit_Click method, you want to grab the row we're going to edit by using the hidden Value field from the dropdown :
PlaceInfo placeToEdit = Context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value))
Assign it the new values, and tell entity framework this model is now modified:
using (var context = new SampleDBEntities())
{
PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value));
placeToUpdate.Name = txtName.Text;
placeToUpdate.Address = txtAddress.Text;
placeToUpdate.Geolocation = DbGeography.FromText("POINT( "+hdnLocation.Value+")");
context.Entry(placeToUpdate).State = EntityState.Modified;
context.SaveChanges();
}
Save the changes to your context and you should be good to go.
I am new to Asp.Net & C#. I am developing a blog. I am able to save images in a folder and the image path in SQL Server. Now I want to retrieve the image from folder whose path is stored in SQL Server table.
I try this:
ASPX markup:
<body>
<form id="form1" runat="server">
<div class="row">
<div class="page-header"></div>
<div class="col-lg-3">
<asp:Image ID="Image1" CssClass="img-thumbnail" runat="server" />
</div>
</div>
</form>
</body>
Code-behind:
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.IO;
using System.Configuration;
namespace Admin_Panel
{
public partial class Admin : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
Image1.ImageUrl ="~/Images/" + filep;
}
con.Close();
}
}
}
But the above code will only show one image.
What I want: I want to show all images using a foreach loop or something like a loop, but I don't know how to do that.
Any help will be appreciated.
First of all, you should use asp.repeater:
<asp:Repeater ID="RptImages" runat="server">
<ItemTemplate>
<asp:Image ID="Img" runat="server" ImageUrl='<%# Container.DataItem %>'/>
</ItemTemplate>
</asp:Repeater>
Else:
public partial class Admin : System.Web.UI.Page
{
List<String> images = new List();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
images.add(String.Concat("~/Images/", filep);
}
con.Close();
RptImages.DataSource = images;
RptImages.DataBind();
}
}
I can't find my label ID in LoginView Control, Just to explain what i'm trying to build. If you are NOT logged in you can only see the content from the database, but if your ARE logged in you can edit it. But right now i just need help to make it read the data from the database
Here is the ASP.NET Code-Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
{
using (SqlConnection connection = new SqlConnection("Data Source=10.138.22.47;Initial Catalog=Student10157;User ID=Studentxxxxx;Password=xxxxxxxxxxxxxxxxx"))
{
connection.Open();
SqlCommand cm = new SqlCommand("Select * from Content_Text", connection);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
lblLeft.text = dr["Text"].ToString();
}
}
}
}
}
Here is my ASP.NET code:
<asp:FormView runat="server" ID="viewdata">
<ItemTemplate>
<asp:LoginView ID="LoginView1" runat="server">
<AnonymousTemplate>
<asp:Label ID="lblLeft" runat="server"></asp:Label>
</AnonymousTemplate>
<LoggedInTemplate>
<asp:TextBox ID="TxBLeft" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
</ItemTemplate>
</asp:FormView>
I have tried as you can see to use a formview with the following C# code but that dont work either var lblLeft = (Label)viewData.FindControl("lblLeft");
Try This.
if (dr.Read())
{
Label lblLeft = (Label)viewData.FindControl("lblLeft")
lblLeft.text = dr["Text"].ToString();
}
FormView need in datasource, so i think you need somethink like this in your code
protected void Page_Load(object sender, EventArgs e)
{
{
using (SqlConnection connection = new SqlConnection("Data Source=10.138.22.47;Initial Catalog=Student10157;User ID=Studentxxxxx;Password=xxxxxxxxxxxxxxxxx"))
{
connection.Open();
SqlCommand cm = new SqlCommand("Select * from Content_Text", connection);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
viewdata.DataSource = new []{new { N = dr["Text"] }};
viewdata.DataBind();
}
}
}
}
and markup
<asp:FormView runat="server" ID="viewdata">
<ItemTemplate>
<asp:LoginView runat="server">
<AnonymousTemplate>
<asp:Label ID="lblLeft" runat="server" Text='<%# Eval("N") %>'></asp:Label>
</AnonymousTemplate>
<LoggedInTemplate>
<asp:TextBox ID="TxBLeft" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
</ItemTemplate>
</asp:FormView>
UPDATE
if you have a few content_text you can try something like this
protected void Page_Load(object sender, EventArgs e)
{
{
using (SqlConnection connection = new SqlConnection("Data Source=10.138.22.47;Initial Catalog=Student10157;User ID=Studentxxxxx;Password=xxxxxxxxxxxxxxxxx"))
{
connection.Open();
SqlCommand cm = new SqlCommand("Select * from Content_Text", connection);
SqlDataReader dr;
dr = cm.ExecuteReader();
List<object> ds = new List<object>();
while (dr.Read())
{
ds.Add(new { N = dr["Text"] });
}
viewdata.DataSource = ds;
viewdata.DataBind();
}
}
}
You need to find the label in it's NamingContainer which is the ItemTemplate of the FormView:
protected void Page_Load(object sender, EventArgs e)
{
if (viewdata.CurrentMode == FormViewMode.ReadOnly)
{
LoginView lv = (LoginView)viewdata.FindControl("LoginView1");
Label lblLeft = (Label)lv.FindControl("lblLeft");
}
}
By the way, you should databind the label only if its not a postback:
if(!IsPostBack && viewdata.CurrentMode == FormViewMode.ReadOnly)
{
LoginView lv = (LoginView)viewdata.FindControl("LoginView1");
Label lblLeft = (Label)lv.FindControl("lblLeft");
using (SqlConnection connection = new SqlConnection("Data Source=10.138.22.47;Initial Catalog=Student10157;User ID=Studentxxxxx;Password=xxxxxxxxxxxxxxxxx"))
{
connection.Open();
using(var cm = new SqlCommand("Select TOP 1 Text from Content_Text", connection))
using(SqlDataReader dr = cm.ExecuteReader())
{
if(dr.Read())
{
lblLeft.Text = dr.GetString(dr.GetOrdinal("Text"));
}
}
}
}
You can find label in LoginView control as following:
LoginView logView = (LoginView)viewdata.FindControl("LoginView1");
Label lblLeft = (Label)logView.FindControl("lblLeft");
lblLeft.Text = "Your text goes here";