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();
}
}
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.
and thank you for taking the time to read my post! It is very much appreciated. I am pretty new to ASP.Net and I am trying to create a simple page where I can search a table on my SQL Server database.
Here is the asp.net code:
<%# Page Language="C#" MasterPageFile="~/PantryAdmin.Master" AutoEventWireup="true" CodeFile="ProductSearch.aspx.cs" Inherits="RampantryF.ProductSearch" %>
<asp:Content runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<div>
<asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:fall16_g8ConnectionString %>" SelectCommand="SELECT * FROM [PRODUCT]"></asp:SqlDataSource>
</div>
</asp:Content>
My code behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RampantryF
{
public partial class ProductSearch : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["fall16_g8ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from PRODUCT where(PRODUCT_NAME like '%' + #PRODUCT_NAME + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#PRODUCT_NAME", SqlDbType.NVarChar).Value = SearchBox.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "PRODUCT_NAME");
GridView2.DataSource = ds;
GridView2.DataBind();
con.Close();
}
}
}
The page loads fine but when you press the 'search' button it just refreshes the page instead of loading the data into the gridview. I am wondering what is going on and how I can fix it.
Let me know if any other information is needed. I am happy to provide it.
Thank you!
few changes done to your code, check how the like parameter assigned
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from PRODUCT where PRODUCT_NAME like #PRODUCT_NAME";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#PRODUCT_NAME", SqlDbType.NVarChar).Value = "%"+ SearchBox.Text + "%";
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds, "PRODUCT_NAME");
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
Also change the AutoGenerateColumns as true in the aspx page.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
</asp:GridView>
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 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";
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)