how to retrieve binary image from database in vb.net and insert the image in grid view - vb.net

How to retrieve a binary image from a database using vb.net and insert the image into a GridView.
This is my DB
image (id as integer , img as varbinary(max))

While you clarify the type of gridview you are referring to, here's how to insert the data in the database:
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
Dim command = New SqlCommand("INSERT INTO yourtable(image) values (#image)", c)
' this is specific to the FileUploadControl but the idea is to get the
'image in a byte array; however you do it, it doesn't matter
Dim buffer(FileUpload1.PostedFile.ContentLength) As Byte
FileUpload1.PostedFile.InputStream.Read(buffer, 0, buffer.Length)
command.Parameters.AddWithValue("#image", buffer)
command.ExecuteNonQuery()
End Using
And assuming you are talking about an ASP .NET app, you can bind the data to the gridview as follows:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<!--Trick to encode the bytes as a BASE64 string-->
<img width="100px" height="100px" src='data:image/png;base64,<%#System.Convert.ToBase64String(Eval("image"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=Your_ConnectionString_GoesHere"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [id], [image] FROM [your_table_name_goes_here]">
</asp:SqlDataSource>

Related

Display image from database asp.net vb

I have database
Id int
img varbinary(MAX) --> image
descr nvarchar(50)
and now I want to display image and description. I use the following code
<div>
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="Id"
DataSourceID="SqlDataSourceH"
CssClass="myGridView"
RowStyle-CssClass="rows"
ShowHeader="false">
<Columns>
<asp:ImageField
DataImageUrlField = "Id"
DataImageUrlFormatString = "Hardware.aspx?Id={0}"
ControlStyle-Width = "100"
ControlStyle-Height = "100"></asp:ImageField>
<asp:BoundField DataField="descr"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource
runat="server"
ID="SqlDataSourceH"
ConnectionString='<%$ ConnectionStrings:ConnectionString %>'
SelectCommand="SELECT [Id], [img], [descr] FROM [Hardware]">
</asp:SqlDataSource>
</div>
but image is not displayed
What should I do to display the picture?
Check /Images/theimage.jpg really exists then you need to go into the database and put the full path in the column img.
Also if it is in the folder /Images/ then you need "../Images/theimage.jpg" to go back to the root folder. Check the value of the url copy it to clipboard and dump it in the address bar and see if it comes up, so http://localhost/(dump url here) if it doesn't come up then you need to check the path and update the url value in database.

Multiple Outputs From One Set of Labels

I am building a website in ASP.NET Web Forms with a SQL Database. The database contains a table with 571 entry's of data.
Output
Source Code
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built FROM Houses ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
}
}
}
}
Database
I want to display all 571 houses to do this I would need a set of labels for each house but is there a way I could have one set of labels like the above code to output all 571 entry's without repeating code.
Try to use a Repeater. This is a special control, which allows to define an inner item layout only once and then bind some data to render multiple blocks looking consistently, but containing the different data.
Repeater has ItemTempalte property, which allows you to wrap all the labels you want to see.
<asp:Repeater ID="rptData" runat="server">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
Then just load the DB rows into repeater:
rptData.DataSource = command.ExecuteReader();
rptData.DataBind();
And finally, in the HTML layout specify mapping for labels to respective columns - like
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
or
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
etc.

visual studio 2010 Getting value from gridview

How do I get the value in a gridview when one hits the "Select" link in a row?
If I have a databound, I can get that value. However I am trying to highlight certain labels.The "HighlightTex" function lets me highlight some words that the user selects.
Here is a snippet: I am trying to get the value of "lblinvnum".
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1" Width="540px"
CssClass="Gridview" >
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField HeaderText="Invnum" ItemStyle-Wrap="False">
<ItemTemplate>
<asp:Label ID="lblInvnum" Text='<%# HighlightText(Eval("Invnum").ToString()) %>' runat="server" />
</ItemTemplate>
...
...
... For the "AmtPaid" listed below, I can Get that value. I cannot figure out how to get the value for "lblInvnum" to the snippet listed above.
<asp:BoundField DataField="AmtPaid" HeaderText="AmtPaid"
SortExpression="AmtPaid" DataFormatString="{0:c}" >
In visual basic, this is how I can get the one above for AmtPaid.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim selectedRow As GridViewRow = gvDetails.Rows(index)
Dim contactCell As TableCell = selectedRow.Cells(1)
Dim contact As String = contactCell.Text
Suggestions?

Sort the Pictures in Datalist Control

I Have a Datalist Control and Reading the pictures from folder and showing them in lightbox from Datalist i am also reading data and time from those pictures.Ist thing is that the datalist is not reading the Date picture taken from the attributes and second is that pictures are not being sorted in desc order of date picture taken.Please anyone tell me how can i complete these taskes.
My data list code is here
<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" RepeatDirection="Horizontal" Width="23%" CellPadding="2" CellSpacing="0" Height="270px" HorizontalAlign="Center">
<ItemTemplate>
<asp:Image Width="200px" height="200px" ID="Image1" ImageUrl='<%# Bind("Name", "~/MMS/1 Box/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" rel="lightbox[roadtrip]" title='<%# DataBinder.Eval(Container.DataItem, "LastWriteTime", "{0:yyyy-MM-dd hh:mm:ss}") %>'
Text="Zoom" NavigateUrl='<%# Bind("Name", "~/MMS/1 Box/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Silver" BorderStyle="Dotted" BorderWidth="1px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
and to read the Images from folder my vb.net code is here
Sub loadimage()
Dim sdir As New DirectoryInfo(MapPath("~/MMS/1 Box"))
Dim file As FileInfo() = sdir.GetFiles()
Dim list As New ArrayList()
For Each file2 As FileInfo In file
If file2.Extension = ".jpg" OrElse file2.Extension = ".gif" OrElse file2.Extension = ".bmp" Then
list.Add(file2)
End If
Next
DataList1.DataSource = list
DataList1.DataBind()
End Sub
Anyone tell me what change should i have to make in code so that my both requirements will be completed as well
Use IComparable to sort your list based on time creation time or whatever attribute you want to sort it.
Here is a link which would help you implement this: http://www.knowdotnet.com/articles/sortarraylistofobjects.html

Updateable Data Grid using Linq to SQL in WinForms

I'm populating a datagrid using Linq--standard kind of stuff (code below). For some reason however my ultraDataGrid is stuck in some kind of read-only mode. I've checked all the grid properties I can think of. Is that a result of binding to a Linq data source? Anyone have example code of an updatable grid that uses Linq?
db = New DataContext
myData = New dataClass
dataUltraGrid.DataSource = From table _
In db.profiles _
Select table.field1, table.field2...
Your really not using a LinqDataSource control... your are binding to a List db.profiles your data grid doesn't know anything about updating or deleting or inserting by just being bound to that list, can I suggets this:
<asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSource1"
AutoGenerateColumns="False" DataKeyNames="FooID">
<Columns>
<asp:BoundField DataField="FooID" HeaderText="FooID" InsertVisible="False"
ReadOnly="True" SortExpression="FooID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="YourDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="Foos">
</asp:LinqDataSource>
Found the solution: use lambda expressions to filter the entity and bind directly to the entity.