I am using facebox on my asp.net web site for my image gallery. when i am uploading images to the gallery, they are saved on my disc and url data is stored in my sql database. After the uploading, my gallery displays thumbnails from the images but not in the order as they are uploaded. I want to display the last uploaded image as first in the gallery (order by last uploaded), but i don't know what i should add in the code.
This is the code:
<body style="background-color:black">
<script type="text/javascript" charset="utf-8">
$(function () {
$('[rel^="FaceBox"]').FaceBox();
});
</script>
<form id="form1" runat="server">
<div class="Znamenitosti" id="Znamenitosti">
<asp:DataList ID="dlImages" runat="server" RepeatColumns="7" CellPadding="3" >
<ItemTemplate>
<div class="boxButton">
<ul class="Gallery" >
<li><a id="A1" href='<%# Eval("ime","~/Sliki/Ohrid/Znamenitosti/{0}") %>' title='<%# "Од "+ Eval("userid")+ ", на " + Eval("datum")+ ", " + Eval("opis")%>' rel="FaceBox[gallery1]" runat="server" >
<asp:Image ID="Image1" ImageUrl='<%# Bind("imethumb", "~/Sliki/Ohrid/Znamenitosti/thumb/{0}") %>' runat="server" Width="140" Height="140" AlternateText='<%# Bind("imeslika") %>' />
</a></li></ul></div>
</ItemTemplate>
</asp:DataList>
</div>
Cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["makbazaConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
if (Request.QueryString["ID"] == "Znamenitosti")
{
//Query to get ImagesName and Description from database
SqlCommand command = new SqlCommand("SELECT ime, imethumb, imeslika, kategorija, datum, opis, slikapateka, thumbpateka, userid FROM Ohrid WHERE kategorija='Znamenitosti' AND grad='Ohrid' ", con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dlImages.DataSource = dt;
dlImages.DataBind();
}
.
.
.
.
con.Close();
}
Is datum your date field?
If so just modify your sqlcommand:
SELECT ime, imethumb, imeslika, kategorija, datum, opis, slikapateka, thumbpateka, userid FROM Ohrid WHERE kategorija='Znamenitosti' AND grad='Ohrid' ORDER BY DESC datum
Cheers,
Bartek
Related
This example is totally what I'm looking for
https://www.aspforums.net/Threads/339115/Searchable-multiselect-DropDownList-from-Database-using-jQuery-Select2-Plugin-in-ASPNet/
And after choose all the countries needed, I will click Submit button. My problem is on how to get all the selected value from ddl1.
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".js-example-placeholder-single").select2({
placeholder: "Select",
allowClear: true
});
});
</script></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<h2>
Upload Attachment
</h2>
<div>
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Attachment : " class="form-control"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" class="form-control"/>
<br /><br />
<asp:Label ID="Label1" runat="server" Text="Plase select Staff No : " class="form-control"></asp:Label>
<asp:DropDownList ID="ddl1" Width="300px" runat="server" multiple="multiple" CssClass="form-control js-example-placeholder-single" ToolTip="Select " OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
</asp:DropDownList>
<br /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload Attachment" OnClick="btnUpload_Click"/>
<br /><br />
</div>
</asp:Content>
And this is C# code behind
private void PopulateDropDownList()
{
String strConnString = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_User";
cmd.Connection = con;
try
{
con.Open();
ddl1.DataSource = cmd.ExecuteReader();
ddl1.DataTextField = "IDName";
ddl1.DataValueField = "StaffNo";
ddl1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string message = "";
string rnonow = DateTime.Now.ToString("yyyyMMdd_hhmmss");
GetUploadRno();
rnoUploaded = rno;
Label4.Text = ddl1.SelectedValue; //this is where i'm stuck on how to call the ddl1 selected value. This code just only get the 1st selected value only eg : Brazil only not the other 2 below.
//below is my trial to get the selected value but fail
//foreach (ListItem item in ddl1.Items)
//{
// if (item.Selected)
// {
// insert statement here
// }
//}
}
Please help. Thank you
You can't use DropDownList for multi-select. Use ListBox e.g.
<asp:ListBox ID="ddl" runat="server" SelectionMode="Multiple" CssClass="form-control js-example-placeholder-single" ToolTip="Select">
</asp:ListBox>
In code-behind:
foreach (ListItem item in ddl.Items)
{
if (item.Selected)
{
var text = item.Text;
var value = item.Value;
}
}
I got the answer by creating a field, and jQuery store the data into it.
$('[id*=ddl1]').on('change', function () {
$('[id*=hfSelected]').val($(this).val());
});
<asp:HiddenField ID="hfSelected" runat="server" />
My problem is when I click on the product page (in URL below). It works good but after some idle time on first click on product menu it wont load product images from database to Repeater control.
I am using Bootstrap and not using update-panel.
Please Refer Below Link.
MySite(See Product Page On First Time And Click After 5 to 10 minute of idle time)
My ASP.net code is
<asp:Repeater ID="rptrProduct" runat="server">
<ItemTemplate>
<div class="portfolio-item col-xs-12 col-sm-4 col-md-3">
<div class="recent-work-wrap hovereffect">
<img id="dtimg1" runat="server" class="img-responsive imggray" src='<%#Eval("ImagePath")%>' alt="" style="height: 185px!Important;" />
<div class="overlay1">
<div class="recent-work-inner">
<a id="aimg2" runat="server" href='<%#Eval("ImagePath")%>' rel="prettyPhoto">
<h2>
<%#Eval("ProductName")%></h2>
</a>
<p>
<a id="adtimg1" runat="server" class="preview" href='<%# string.Format("~/BMSubProduct.aspx?pro={0}", Eval("ProductId")) %>'>
<i class="fa fa-eye"></i>View Products</a>
</p>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I am just not getting that why on first time it won't load any images.
my C# page code is
if(!Page.IsPostBack)
{
DataTable dt = DBMaster.getQueryDataTableSchema(query);
if (dt.Rows.Count > 0)
{
string path = GlobalFunction.getPath(1);
NoProducts.Visible = false;
for (int i = 0; i < dt.Rows.Count; i++)
dt.Rows[i]["ImagePath"] = path + Convert.ToString(dt.Rows[i] ["ImagePath"]);
rptrProduct.DataSource = dt;
rptrProduct.DataBind();
}
else
{
NoProducts.Visible = true;
rptrProduct.DataSource = null;
rptrProduct.DataBind();
}
}
public static DataTable getQueryDataTableSchema(string query)
{
try
{
using (IDbConnection con = sq.Open())
{
IDbCommand cmd = con.CreateCommand();
cmd.CommandText = query;
IDbDataAdapter adp = sq.GetAdapter(cmd);
DataSet ds = new DataSet();
adp.FillSchema(ds, SchemaType.Source);
adp.Fill(ds);
con.Close();
return ds.Tables[0];
}
}
catch (Exception ex)
{
return new DataTable();
}
}
and masterpage code in page_load is
if (!Page.IsPostBack)
{
SQLString.Config = myconnectionString;
}
Here NoProduct => No Products Are Available Right Now.
I have tried many things like below:
EnableViewState="true" And EnableViewState="false" both for repeater and in page also.
Change connection string in web.config like
name="SQLConStr" connectionString="Server=localhost;Database=databasename; Uid = username; Pwd = password; Pooling = false; Connection Timeout = 30"
Here tried with and without connection timeout and pooling.
Note: Using MySQL database and using interface to open database connection.
Thanks in advance.
EnableViewState="true"
and try to use
<asp:Image and <asp:HyperLink controls
instead of
img and a tags with runat="server".
Or maybe I don't need to, I don't know. Here's what I'm trying to do. I have a gridview on one page and when I click on an item, it takes the ID and links it to another page that displays all the info that goes with the item in the gridview. On the second page, I want to be able to insert a photo with some text into my database, but I want to make sure it inserts with the proper blogID (that was clicked on from the first page). Here's my code so far:
EditBlogPosts.aspx
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateEditButton="True"
DataSourceID="AccessDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID"
AlternatingRowStyle-BackColor="Gray"
AlternatingRowStyle-CssClass="editGridFormat" RowStyle-CssClass="editGridFormat"
RowStyle-VerticalAlign="Top"
onselectedindexchanged="GridView1_SelectedIndexChanged">
Code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Response.Redirect("~/EditThisPost.aspx?ID=" + row.Cells[2].Text);
}
EditThisPost.aspx
<asp:FormView ID="Formview1" runat="server" DefaultMode="Insert" DataSourceID="AccessDataSource1" >
<InsertItemTemplate>
<br />
<asp:Label ID="TextforPhotoLabel" runat="server" Text="Put your text to go with your photo here:" /><br />
<asp:TextBox ID="PhotoText" runat="server" Rows="10" Columns="100" /><br /><br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="UploadStatusLabel" runat="server" Text="Status: " /><br />
<asp:Button ID="UploadButton" runat="server" OnClick="UploadFile" Text="Insert Item" /><br />
</InsertItemTemplate>
</asp:FormView>
Code behind (paying special attention to the line where I declare int blogID):
protected void UploadFile(object sender, EventArgs e)
{
TextBox txtPhotoText = (TextBox)Formview1.FindControl("PhotoText");
FileUpload FileUpload1 = (FileUpload)Formview1.FindControl("FileUpload1");
Label UploadStatusLabel = (Label)Formview1.FindControl("UploadStatusLabel");
if (FileUpload1.HasFile)
{
try
{
if (FileUpload1.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload1.PostedFile.ContentLength < 10240000)
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/photos/PeoplePhotos/") + filename);
UploadStatusLabel.Text = "Upload status: Complete!";
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO BlogEntryItems (BlogID, Picture, PicText1) VALUES (?,?,?)";
int blogID = int.Parse(Request.QueryString["ID"]);
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#BlogID", blogID);
com.Parameters.AddWithValue("#Picture", filename);
com.Parameters.AddWithValue("#PicText1", txtPhotoText);
com.ExecuteNonQuery();
con.Close();
}
else
UploadStatusLabel.Text = "Upload status: The file has to be less than 10 MB!";
}
else
UploadStatusLabel.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
UploadStatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
I truly appreciate any help. I was thinking I could somehow get the ID that was passed to make the "~\EditThisPost.aspx?ID=" a valid link. But if there is a better way to do it or if the way I'm thinking doesn't even exist, then how can I accomplish what I need?
you can get the blogID as below
int blogID = int.Parse(Request.QueryString["ID"]);
I would use int.TryParse to avoid exceptions in case of non integer values in the query string
int blogID;
int.TryParse(Request.Querystring["ID"], out blogID);
add a Viewstate-backed property to EditThisPost.aspx to hold BlogID: -
http://www.codingwith.net/2008/01/viewstate-backed-properties-part-one.html
Set this property in PageLoad of EditThisPost.aspx, and then use it in UploadFile.
I have this code:
$(document).ready(function () {
$('#Priroda').hide();
$('#priroda_').click(function () {
$('#Znamenitosti').hide();
$('#Priroda').show();
});
$('#znamenitosti_').click(function () {
$('#Priroda').hide();
$('#Znamenitosti').show();
});
});
</script>
<div class="meni">
<nav>
<ul>
<li class="active">Info</li>
<li>Znamenitosti</li>
<li>Priroda</li>
<li>Noken Zivot</li>
</ul>
</nav>
</div>
where I have few categories in the menu. When i click on specific category, i want to show the (div) tag for that specific category within the same .aspx page, and the other (div) tags for the other categories should be hidden.
This is the (div) tag for the category "Priroda":
<div class="Priroda" id="Priroda">
<asp:DataList ID="DataList1" runat="server" RepeatColumns="7" CellPadding="3">
<ItemTemplate>
<div class="boxButton">
<ul class="Gallery">
<li><a id="A1" href='<%# Eval("ime","~/Sliki/Ohrid/Priroda/{0}") %>' title='<%# "Од "+ Eval("userid")+ ", на " + Eval("datum")+ ", " + Eval("opis")%>' rel="FaceBox[gallery1]" runat="server" >
<asp:Image ID="Image1" ImageUrl='<%# Bind("ime", "~/Sliki/Ohrid/Priroda/{0}") %>' runat="server" Width="140" Height="140" AlternateText='<%# Bind("imeslika") %>' />
</a></li></ul></div>
</ItemTemplate>
</asp:DataList>
</div>
For binding the DataList i used this code in .cs file:
protected void BindDataList1()
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["makbazaConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
//Query to get ImagesName and Description from database
SqlCommand command = new SqlCommand("SELECT ime, imeslika, kategorija, datum, opis, slikapateka, userid FROM Ohrid WHERE kategorija='Priroda'", con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dlImages.DataSource = dt;
dlImages.DataBind();
con.Close();
}
Now i don't know how to call BindDataList1(); to show me data when i click on that category. I have different BindDataLists for each category. Can you tell me how to call specific BindDataList for the category that is selected from the menu? For example when i click on link Priroda show me the (div) tag Priroda and BindDalaList1();, when i click on link Znamenitosti show me the (div) tag Znamenitosti and BindDalaList2();
I think a simple way to do this would be to run your databind functions for all categories at once, for example in the PreRender event of "DataList1", so all of the data is on the page, and each bit is just hidden or shown through your jQuery.
Alternatively, could you use instead of tags, and have an OnClick property set to call your DataBind1 method.
i'm creat db in sql like this
ImageId Int(set identity property=true)
ImageName Varchar(50)
Image image
and my aspx like this
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Inserting images into databse and displaying images with gridview</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:500px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Image Name:
</td>
<td>
<asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Upload Image:
</td>
<td>
<asp:FileUpload ID="fileuploadImage" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
my code like this
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
/// <summary>
/// btnUpload_Click event is used to upload images into database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting length of uploaded file
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
/// <summary>
/// function is used to bind gridview
/// </summary>
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
but when run this application
this error exsiption appear
Cannot insert the value NULL into column 'ImageId', table 'DressDB .dbo.Image'; column does not allow nulls. INSERT fails.
The statement has been terminated.
how i can solve that please?
Mahmoud Gamal is correct, however if you feel more comfortable doing it with the design-view in Management Studio, this is the option you are looking for:
That will set the value for the first inserted row to 1, and then increase that counter by 1 for each new row inserted to the table.
The error is pretty clear. You can't insert NULL Values in this column because it doesn't allow NULL values.
how i can solve that please?
Make this column ImageId auto incremental like so:
ALTER TABLE Images
ALTER IMAGE_ID INT NOT NULL IDENTITY(1, 1);
Then your INSERT statement:
INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)
Should work properly.
But in your case where the table already contains data, you can't do that directly as pointed out by #Damien_The_Unbeliever. In this case1:
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
See the following question for more details:
Adding an identity to an existing column.
1 Quoted From this answer