Displaying multiple image from SQL Server 2008 - c#

I need to display multiple images from a database table and bind it to a repeater, how do I go about doing it?
This is my current code, but I have no idea on how to proceed to display images
Below is my method to load data to the repeater:
public void loadNoofNewJobsCompany()
{
DateTime lastlogged = Convert.ToDateTime(Session["LastLoginstaff"]);
string sqlStr = "SELECT * FROM Job ";
sqlStr += "WHERE ";
sqlStr += "UpdatedDateCmpRep <= #loggedin";
SqlCommand cmd = new SqlCommand(sqlStr, cnn);
cmd.Parameters.AddWithValue("#loggedin", lastlogged);
try
{
cnn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Label2.Text = dt.Rows.Count.ToString();
PagedDataSource pgdsc = new PagedDataSource();
pgdsc.DataSource = dt.DefaultView;
repeater1.DataSource = pgdsc;
repeater1.DataBind();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
finally
{
if (cnn != null)
{
cnn.Close();
}
}
}
This is the repeater:
<asp:Repeater ID="repeater1" runat="server">
<ItemTemplate>
<div class="boxgrid caption">
<%--<img src="../../img/google.png" style="text-align:center"/>--%>
<div class="cover boxcaption">
<p>
<a href='../Job/ViewJobDetail.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "JobID")%>' class="headerlink">
<%# getTitle(Eval("JobName").ToString()) %>
</a>
</p>
<p>
Salary Range:
<%# DataBinder.Eval(Container.DataItem, "JobSalaryRange")%>
</p>
... (more stuff - not relevant here) .....
</div>
</div>
</ItemTemplate>
</asp:Repeater>

For displaying images in gridview we need to create a Handler to read binary data from database.
here is good example of it.

I am assuming that the images are stored in the database.
Write .ashx(Http handler) to display the image.You can render the image using Response Header in the .ashx file directly from the database and use that .ashx file as follow in your repeater,the images will get displayed.
<img src="displayImage.ashx?id=111" style="text-align:center"/>

one more good example to look at
Display Images from database in ASP.NET GridView using HttpHandler

Related

How to insert multiple different textboxes to database table one by one for each row?

I have 3 different textboxes for serials. And when I click the button I want to save them for each row in database table.
Textbox1.Text="HP" ==> STOCKID
Textbox2.Text="İ5" ==> MODEL
Textbox3.Text="3" ==> QUANTITY
Textbox4.Text="11231231"; ==> SERIAL-1
Textbox5.Text="11231231"; ==> SERIAL-2
Textbox6.Text="11231231"; ==> SERIAL-2
Then Button click event.
Result should be as below.
FIRST GRIDVIEW
STOKID
MODEL
QUANTİTY
HP
I5
3
SECOND GRIDVIEW
STOKID
MODEL
SERIALS
DELETEBUTTON
HP
I5
32165161
BUTTON
HP
I5
12313223
BUTTON
HP
I5
16516516
BUTTON
When I delete from serials one bye one, the first Gridview QTY should decrease one for each serials. Is it possible?
I use store procedure during insert to data for first gridview. But for second one I don't know how to use a loop for textboxes and add to database different serials(textboxes values).
Ok, so say this markup:
We have Stokkid, model, and then have 3 optional serial num boxes
(if they are left blank - we don't add).
So, this markup:
The boxes, and add button:
<div style="float: left">
<h4>Stokid</h4>
<asp:TextBox ID="txtStokID" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Model</h4>
<asp:TextBox ID="txtModel" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Serial 1</h4>
<asp:TextBox ID="txtS1" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Serial 2</h4>
<asp:TextBox ID="txtS2" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Serial 3</h4>
<asp:TextBox ID="txtS3" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px;margin-top:20px">
<asp:Button ID="cmdSave" runat="server" Text="Save/Add" CssClass="btn"
OnClick="cmdSave_Click"
/>
</div>
<div style="clear:both" ></div>
And right below that, 2 grids, the first totals gv, and then the data we have gv.
So, this:
<h3>Counts</h3>
<asp:GridView ID="GVCounts" runat="server" CssClass="table"
width="40%" ShowHeaderWhenEmpty="True" >
</asp:GridView>
<h3>Items</h3>
<asp:GridView ID="GridView1" runat="server" CssClass="table"
width="40%" ShowHeaderWhenEmpty="True" >
</asp:GridView>
And now our code to load up the above:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
// load up "counts" grid
string strSQL =
#"SELECT Stokid, Model, count(*) as QTY FROM tblSerials
GROUP BY Stokid, Model";
GVCounts.DataSource = MyRst(strSQL);
GVCounts.DataBind();
// Load up existing data grid
strSQL =
#"SELECT Stokid, Model, Serials FROM tblSerials ORDER BY ID";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
So, only part left is the "add new data button"
That code is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// save (add) one row for each serial number,
// if no serial - then don't add
DataTable dt = MyRst("SELECT * FROM tblSerials WHERE ID = 0");
DataRow MyAddRow = dt.NewRow();
MyAddRow["Stokid"] = txtStokID.Text;
MyAddRow["Model"] = txtModel.Text;
MyAddRow["Serials"] = txtS1.Text;
dt.Rows.Add(MyAddRow);
if (txtS2.Text != "")
{
MyAddRow = dt.NewRow();
MyAddRow["Stokid"] = txtStokID.Text;
MyAddRow["Model"] = txtModel.Text;
MyAddRow["Serials"] = txtS2.Text;
dt.Rows.Add(MyAddRow);
}
if (txtS3.Text != "")
{
MyAddRow = dt.NewRow();
MyAddRow["Stokid"] = txtStokID.Text;
MyAddRow["Model"] = txtModel.Text;
MyAddRow["Serials"] = txtS3.Text;
dt.Rows.Add(MyAddRow);
}
// send/save all rows to database
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblSerials", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(dt);
}
}
// Update counts and display
LoadData();
}
so, the result is now this:
Now, we do probably want to setup a delete button.
so, that means our "cheat" life and easy GV of data?
Well, we have to give it a bit more effort, love and care.
We need the database PK id, and we want that delete button.
And since the delete button can be a danger, then it should confirm.
So, we have to update our GV a bit, bite the bullet and use some templating. but, it is not much.
And lets use a boot-strap icon - they should be part of any most recent project by defualt. But BE warned, after boottrap 4, the later versions (due to some copyright/lawsuit, bootstrap does not include the glyph-icons).
Anyway, I COULD use a plain jane asp.net button in the gv for delete, but lets use standard html button - I ONLY use the html one, since I wanted the cute icon. Probably better for you to use a image button.
(code is much the same either way).
So, our 2nd gv now looks like this:
<h3>Items</h3>
<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover"
width="40%" ShowHeaderWhenEmpty="True" DataKeyNames="ID"
AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="STOKID" HeaderText="STOKID" />
<asp:BoundField DataField="MODEL" HeaderText="MODEL" />
<asp:BoundField DataField="serials" HeaderText="serials" />
<asp:TemplateField HeaderText="Delete" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<button id="cmdDelete" runat="server" class="btn"
onclick="if (!confirm('Delete')) return false;"
onserverclick="cmdDel_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-trash"></span>
</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code to load up this gv is now:
void LoadData()
{
// load up "counts" grid
string strSQL =
#"SELECT Stokid, Model, count(*) as QTY FROM tblSerials
GROUP BY Stokid, Model";
GVCounts.DataSource = MyRst(strSQL);
GVCounts.DataBind();
// Load up existing data grid
strSQL = #"SELECT * FROM tblSerials ORDER BY ID";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
And our delete code is this:
protected void cmdDel_ServerClick(object sender, EventArgs e)
{
HtmlButton btn = (HtmlButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
string strSQL = "DELETE FROM tblSerial WHERE ID = {PKID}";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
// update count and items gv
LoadData();
}
So, now we see, get this for a delete:
Edit2: The Myrst routine
In a few places in above, I also used this helper routine, since I get VERY tired VERY fast having to write code each and every time I want some data, so, I wrote and use this routine:
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
It handy for filling out a gridview, dropdown list etc.

asp.net image src not showing from database in listview

I am facing very rear problem. I am trying to bind images path from database using listview control. Listview gets bind but img is not showing up. When I look at inspect I cant's see src attribute in img tag. Listview gets bind perfectly and path is also correct. If you see below screenshot & see the highlighted line which is that img tag which is missing src attribute.
<div class="row">
<asp:ListView ID="subCategoriesList" runat="server">
<ItemTemplate>
<div class="col-md-3">
<img id="myimag" runat="server" src='<%# Eval("icon") %>' />
<br /><%# Eval("name") %>
</div>
</ItemTemplate>
</asp:ListView>
</div>
ListviewBind Code
private void bindSubCatgoriesRightSide()
{
try {
string constr = ConfigurationManager.ConnectionStrings("conio2").ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr)) {
using (MySqlCommand cmd = new MySqlCommand()) {
cmd.CommandText = "SELECT * FROM subcategory WHERE type = 'product' and category = 'mobile' and status = 'active'";
cmd.Connection = con;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd)) {
DataTable dt = new DataTable();
sda.Fill(dt);
subCategoriesList.DataSource = dt;
subCategoriesList.DataBind();
}
}
}
} catch (Exception ex) {
Response.Write(ex);
}
}
I think you're looking at the wrong output section, in your listview item template, you are wrapping the image in <div class="col-md-3"></div ...
but in the screenshot, the image is wrapped in <div class="col-md-6 col-sm-6 col-xs-12 margin-bottom"></div
Unless you are changing the classes with JS

After some idle time images not load from database

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".

Order gallery images as they are uploaded

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

How to use repeater inside the repeater

It's possible to use repeater inside the another repeater? How?
my problem is, the back-end can't see the repeater inside the repeater.
FRONT:
<div id="blogright">
<ul class="accordion">
<asp:Repeater ID="parentRep" runat="server">
<ItemTemplate>
<li class="2010">
<%# Eval("DYear") %><span><%# Eval("PCount") %></span>
<ul class="sub-menu">
<asp:Repeater ID="childRep" runat="server">
<ItemTemplate>
<li><em><%# Eval("DDay") %></em><%# Eval("DMonth") %><span><%# Eval("ICount") %></span></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
BACK:
//This is for parentRep
daString = "SELECT datepart(YEAR,BLG_DATE) as DYear,COUNT(BLG_DATE) as PCount FROM [BLG] INNER JOIN [ACC] ON [BLG].ACC_ID=[ACC].ACC_ID WHERE [BLG].ACC_ID='"+userID+"' GROUP BY BLG_DATE";
SqlDataAdapter da2 = new SqlDataAdapter(daString, conn);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
parentRep.DataSource = dt2;
parentRep.DataBind();
//This is for childRep
dt.Clear();
daString = "SELECT DATEPART(DAY,BLG_DATE) as DDay,datename(month,BLG_DATE) as DMonth,DATEPART(YEAR,BLG_DATE) as DYear FROM [BLG] INNER JOIN [ACC] ON [BLG].ACC_ID=[ACC].ACC_ID WHERE [BLG].ACC_ID='"+userID+"' and BLG_DATE like '%"+urlId+"%'";
SqlDataAdapter da3 = new SqlDataAdapter(daString, conn);
DataTable dt3 = new DataTable();
da2.Fill(dt3);
//can't see the childRep here.
Sorry for my English.
You can get a reference to the child Repeater and bind data to it in the ItemDataBound event this way:
protected void parentRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater childRepeater = (Repeater)e.Item.FindControl("childRep");
childRepeater.ItemDataBound += new RepeaterItemEventHandler(childRepeater_ItemDataBound);
childRepeater.ItemCommand += new RepeaterCommandEventHandler(childRepeater_ItemCommand);
childRepeater.DataSource = dt3; //dt3 is the DataTable from your code sample
childRepeater.DataBind();
}
}
Additionally, there are some very thorough answers in this thread: Repeater in Repeater

Categories