Retrieving an Image from SQL using C# to an asp:Image - c#

I am trying to retrieve an image from SQL Server 2008 Express and insert it into an <ASP:Image>. I have tried using a MemoryStream but I just can't seem to get it right.
My C# code at the minute looks like:
try
{
con.Open();
SqlCommand sqlGetStep1 = new SqlCommand("staff_getStep1", con);
{
sqlGetStep1.CommandType = CommandType.StoredProcedure;
sqlGetStep1.Parameters.Add(new SqlParameter("#taskID", Convert.ToInt16(taskID)));
SqlDataReader step1 = sqlGetStep1.ExecuteReader();
//Check if username exists
if (step1.Read())
{
step1Text = (string)step1["step1Text"];
step1Image = (byte)step1["step1Image"];
}//if
else
{
step1Text = "null";
step1Image = 0;
}//else
}//sqlDeleteNotification
}//try
catch (SqlException sqlEx)
{
lblSQLError.Visible = true;
lblSQLError.Text = sqlEx.Message.ToString();
}//catach sql
catch (Exception ex)
{
lblError.Visible = true;
lblError.Text = ex.ToString();
}//Catch exception
finally
{
con.Close();
}//Finally
My aspx code where I would like to display the image looks like:
<asp:Panel runat="server" ID="pnlStep1" Visible="false" CssClass="NormalText">
<asp:Label runat="server" ID="lblStep1Text" Text="Step 1 Instruction: "></asp:Label>
<asp:TextBox runat="server" ID="txtStep1Text" Text="" ReadOnly="true"></asp:TextBox>
<asp:Label runat="server" ID="lblStep1Image" Text="Step 1 Image: "></asp:Label>
<asp:Image runat="server" ID="imgStep1" ImageUrl="" Height="100px" Width="100px"/>
</asp:Panel>
Any help would be greatly appreciated :)

You need to have a separate url that takes the id of the image to be delivered (in this case the step id) and delivers the contents as the results with the correct MIME type. Use the url to this method as the url for the asp:Image. Normally, you'd implement this (in WebForms) as a HttpHandler. See How to return an image as the response in ASP.NET

Related

Multiple Images upload with different titles

My Requirement is. I will be uploading 3-4 images at a time through FileUpload. Each Image will have its own Title, Descriptions etc.
Now my issue is that, whenever uploading I have given a title column for the images. But when I upload 3-4 Images the title and description is going same for all the images.
Here Is my HTML for the Image Uploading via FileUpload.
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label1" runat="server">Image Title</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:textbox id="txtImagetitle" cssclass="form-control" runat="server" validationgroup="AddNew"></asp:textbox>
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator1" runat="server"
controltovalidate="txtImagetitle" errormessage="Please add the image title" validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label2" runat="server">Image description</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:textbox id="txtImagedesc" cssclass="form-control" runat="server" validationgroup="AddNew"></asp:textbox>
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator2" runat="server"
controltovalidate="txtImagedesc" errormessage="Please add the image description"
validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label3" runat="server">Image upload</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:fileupload id="FileUpload1" runat="server" allowmultiple="true" />
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator3" runat="server"
controltovalidate="FileUpload1" errormessage="Please add the gallery date" validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
Please suggest what to do in this case when uploading multiple images how to set different titles for different Images.
UPDATED CODE BEHIND
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Request.QueryString.Count > 0)
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename));
using (SqlConnection conn = new SqlConnection(conString))
if (Request.QueryString["Id"] != null)
{
string Id = Request.QueryString["Id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = " Update tbl_galleries_stack SET gallery_id=#gallery_id,img_title=#img_title,img_desc=#img_desc,img_path=#img_path, IsDefault=#IsDefault Where Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#gallery_id", ddlgallery.SelectedValue);
cmd.Parameters.AddWithValue("#img_title", txtImagetitle.Text);
cmd.Parameters.AddWithValue("#img_desc", txtImagedesc.Text);
cmd.Parameters.AddWithValue("#img_path", filename);
cmd.Parameters.AddWithValue("#IsDefault", chkDefault.Checked);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery updated sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_galleries_stack (gallery_id,img_title,img_desc,img_path,IsDefault) values(#gallery_id,#img_title, #img_desc, #img_path,#IsDefault)", conn);
cmd1.Parameters.Add("#gallery_id", SqlDbType.Int).Value = ddlgallery.SelectedValue;
cmd1.Parameters.Add("#img_title", SqlDbType.NVarChar).Value = txtImagetitle.Text;
cmd1.Parameters.Add("#img_desc", SqlDbType.NVarChar).Value = txtImagedesc.Text;
cmd1.Parameters.Add("#img_path", SqlDbType.NVarChar).Value = filename;
cmd1.Parameters.Add("#IsDefault", SqlDbType.Bit).Value = chkDefault.Checked;
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery added sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
}
There is no way you can give different title / description as you have given no option to provide it. Period.
You are forced to use multiple fileupload controls. This is also tricky because asp:FileUpload controls wont maintain their state after postback.
So, the solution I can see is a two-part one. Create two panels and hide the second panel at page load
Part 1
Place a label and textbox and button like this in the first panel in your page.
When the user enters a value, say 10, and fires EnterButton_click close Panel1 and open Panel2.
Part 2
On Panel 2, place a GridView like this
<asp:GridView ID="ImagesGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Sl No">
<ItemTemplate><%# Container.DisplayIndex + 1 %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:TextBox ID="txtTitle" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:FileUpload ID="flUpload" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="SaveButton" Text="Save" runat="server" OnClick="SaveButton_Click"/>
Now on the Enter buttons click event on Panel 1, write this.
// the idea is to create an empty gridview with number of rows client selected
protected void EnterButton_Click(object sender, EventArgs e)
{
//in this, 10 has been entered
var imageCount = Convert.ToInt32(txtImageCount.Text);
//var list = new List<string>();
//for (int i = 0; i < imageCount; i++)
//{
// list.Add(string.Empty);
//}
var list = new List<string>(10);
list.AddRange(Enumerable.Repeat(String.Empty, imageCount));
ImagesGrid.DataSource = list;
ImagesGrid.DataBind();
//TO DO: hide panel1 and make panel2 visible
}
So on clicking enter, you will get an empty gridview with ten rows.
Now fill the rows in the GridView, do validation and hit Save. On Save Button click event, you can access the WebControls like this.
protected void SaveButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in ImagesGrid.Rows)
{
var title = row.FindControl("txtTitle") as TextBox;
var description = row.FindControl("txtDescription") as TextBox;
var imageFile = row.FindControl("flUpload") as FileUpload;
string filename = Path.GetFileName(imageFile.FileName);
imageFile.SaveAs(Server.MapPath("/GalleryImages/" + filename));
//TO DO: write save routine
}
}
It looks like you only have one set of inputs tied to a single file upload with multiple turned on.
You will either want to turn off multiple and allow the user to add reported sets of those images, or have the editing of title, etc happen in a gridview with the upload.
You could also support a"holding cell " where they upload and then must enter that information before you actually save it to your data store.

Perform a SQL query search based on one or both user inputs and populate a grid view with the results

I am working on a small search form that has two text fields: One that allows users to search for a job list (which is basically a wish list--don't know why they want to call it a "job list" but whatever) by entering in part of or a full email address or someone's first and/or last name (This textbox is called SearchName). This field is required and if it is blank when the user hits "Search," an error message appears telling them so. The second textbox is optional, and it allows users to enter in a city or a state to help narrow their search down even more (this textbox is called SearchLocation).
I have a function (called getJobLists()) that is used by the search button to get results.
As it is right now, the part of the function that returns results based on what is entered into the SearchName field works perfectly. However, I cannot get any results for SearchLocation. When I enter a valid email or name into SearchName, then enter a valid city or state into SearchLocation, I get no results. However, if I enter in anything invalid (i.e. a city that is not associated with the entered email or name) the "no results found" message does appear.
I have tested both SQL queries in my search function in SQL Server Management Studio and they do work perfectly.
I have a try-catch inside the search function, but no error is being shown, not even in the console.
This is the code behind:
protected void Page_Load(object sender, System.EventArgs e)
{
// CHECK IF THE WISHLIST SEARCH ENABLED
StoreSettingsManager settings = AbleContext.Current.Store.Settings;
if (!settings.WishlistSearchEnabled)
{
Response.Redirect(AbleCommerce.Code.NavigationHelper.GetHomeUrl());
return;
}
}
protected void getJobLists()
{
try
{
if (SearchName.Text != "")
{//if SearchName.Text is not blank
if (SearchLocation.Text != "")
{//check to see if SearchLocation.Text is not blank either
string sqlSelect = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%') AND ((City + Province) LIKE '%'+#Location+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.Parameters.AddWithValue("#Location", String.Format("%{0}%", SearchLocation.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl = ds.Tables.Add("jobsListsTbl");
jobsListsTbl.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl.NewRow();
dr["User"] = reader["Name"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl";
WishlistGrid.DataBind();
}
}//end of if(SearchLocation.Text !='')
else
{//if SearchLocation.Text is blank, then go with this code instead
string sqlSelect2 = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect2, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl2 = ds.Tables.Add("jobsListsTbl2");
jobsListsTbl2.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl2.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl2.NewRow();
dr["User"] = reader["UserName"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl2.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl2";
WishlistGrid.DataBind();
}
}//end if SearchLocation.Text is empty
}//end of if SearchName.Text !==''
}
catch (Exception x)
{
errors5.Text += "ERROR: " + x.Message.ToString() + "<br />";
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
WishlistGrid.Visible = true;
getJobLists();
}
And this is the designer code for the search form (Note: the NavigateUrl is not set for the hyperlink yet. I will set it once everything is displaying properly for the search results):
<div id="findWishlistPage" class="mainContentWrapper">
<div class="section">
<div class="introDiv">
<div class="pageHeader">
<h1>Find a Job List</h1>
</div>
<div class="content">
<asp:label id="errors" runat="server" text=""></asp:label>
<asp:label id="errors2" runat="server" text=""></asp:label>
<asp:label id="errors3" runat="server" text=""></asp:label>
<asp:label id="errors4" runat="server" text=""></asp:label>
<asp:label id="errors5" runat="server" text=""></asp:label>
<asp:UpdatePanel ID="Searchajax" runat="server">
<ContentTemplate>
<asp:Panel ID="SearchPanel" runat="server" EnableViewState="false" DefaultButton="SearchButton">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableViewState="false" />
<table class="inputForm">
<tr>
<th class="rowHeader">
<asp:Label ID="SearchNameLabel" runat="server" Text="Name or E-mail:" AssociatedControlID="SearchName" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:Textbox id="SearchName" runat="server" onfocus="this.select()" Width="200px" EnableViewState="false"></asp:Textbox>
<asp:RequiredFieldValidator ID="SearchNameValdiator" runat="server" ControlToValidate="SearchName"
Text="*" ErrorMessage="Name or email address is required." EnableViewState="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="rowHeader">
<asp:Label ID="SearchLocationLabel" runat="server" Text="City or State (optional):" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:TextBox id="SearchLocation" runat="server" onfocus="this.select()" Width="140px" EnableViewState="false"></asp:TextBox>
<asp:LinkButton ID="SearchButton" runat="server" CssClass="button linkButton" Text="Search" OnClick="SearchButton_Click" EnableViewState="false" />
</td>
</tr>
</table><br />
<asp:GridView ID="WishlistGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" ShowHeader="true"
SkinID="PagedList" Visible="false" EnableViewState="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderStyle CssClass="wishlistName" />
<ItemStyle CssClass="wishlistName" />
<ItemTemplate>
<asp:HyperLink ID="WishlistLink" runat="server" >
<%#Eval("User")%>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<HeaderStyle CssClass="wishlistLocation" />
<ItemStyle CssClass="wishlistLocation" />
<ItemTemplate>
<asp:Label ID="Location" runat="server" Text='<%#Eval("PrimaryAddress")%>'></asp:Label>
<%--'<%#GetLocation(Eval("User.PrimaryAddress"))%>'--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Localize ID="EmptySearchResult" runat="server" Text="There were no job lists matching your search criteria."></asp:Localize>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
Can anyone please tell me what I'm missing or doing wrong?
Okay, I finally solved the issue. Apparently, it was a variable naming issue I kept overlooking. But now it all works okay! :)

asp.net RequiredFieldValidator

I have a problem.
I have a registration and some RequiredFieldValidator controlls.
Problem:
If i leave the textbox empty, then i can see the errormessage. But it write the values in my database. i want that it stops, and not writing the values in my DB.
Thank you very much!
Kevin
Aspx
<tr>
<td id="LabelBenutzername" class="auto-style2">Benutzername</td>
<td>
<asp:TextBox ID="TextBoxRBenutzername" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBoxRBenutzername"
ErrorMessage="Bitte einen Benutzernamen eingeben" ForeColor="Red">
</asp:RequiredFieldValidator>
</td>
</tr>
Codebehind
if (IsPostBack)
{
SqlCommand cmd = new SqlCommand("select * from tabUser where Benutzername = #Benutzername", con);
SqlParameter param = new SqlParameter();
param.ParameterName = "#Benutzername";
param.Value = TextBoxRBenutzername.Text;
cmd.Parameters.Add(param);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Label1.Text = "User Id already exists";
con.Close();
return;
}
con.Close();
}
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBFitnessBlogConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //assigning connection to command
cmd.CommandType = CommandType.Text; //representing type of command
//cmd.CommandText = "INSERT INTO UserDetails (Fname,Lname,Email,Password,Gender,Dob,Mobile,Address) values
// (#Fname,#Lname,#Email,#Password,#Gender,#Dob,#Mobile,#Address)";
cmd.CommandText = "INSERT INTO tabUser values(#Benutzername,#Passwort,#Vorname,#Nachname,#Email)";
//adding parameters with value
cmd.Parameters.AddWithValue("#Benutzername", TextBoxRBenutzername.Text.ToString());
cmd.Parameters.AddWithValue("#Passwort", TextBoxRPasswort.Text.ToString());
cmd.Parameters.AddWithValue("#Vorname", TextBoxRVorname.Text.ToString());
cmd.Parameters.AddWithValue("#Nachname", TextBoxRNachname.Text.ToString());
cmd.Parameters.AddWithValue("#Email", TextBoxREmail.Text.ToString());
con.Open(); //opening connection
cmd.ExecuteNonQuery(); //executing query
con.Close(); //closing connection
Label1.Text = "Registration erfolgreich..";
}
catch (Exception ex)
{
Label1.Text = "Registration erfolgreich NICHT..";
}
}
In your code-behind, wrap the database logic in a check to see if the page is valid or not, like this:
if(Page.IsValid)
{
// Do database logic here
}
Quick answer: In your code-behind file, write into the event to check for validation prior to proceeding with the database update.
protected void btnUpdateSettings_Click(object sender, EventArgs e)
{
if (IsValid)
{
// Event Programming Code Goes Here
}
}
The idea would be that if any controls had triggered validation controls, then the form could post-back, but then there would be no code execution.
Before you make your call to the database to update your data, check
Page.IsValid == true
before you make your update.
This should be false if your validation failed.
I don't see your submit button. But I have used your code to show you how I do mine. It looks like you are missing the ValidationGroup in both controls.
<tr>
<td id="LabelBenutzername" class="auto-style2">Benutzername</td>
<td>
<asp:TextBox ID="TextBoxRBenutzername" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBoxRBenutzername" ValidationGroup="Insert" ErrorMessage="Bitte einen Benutzernamen eingeben" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Font-Size="Smaller" Height="29px" OnClick="btnSubmit_Click" Width="59px" ValidationGroup="Insert" CausesValidation="true" />
</td>
</tr>
I hope this helps.
Note that you can also use a validation summary.

Displaying Database Images in Gridview with HttpHandler

I am trying to use an ashx page as a http handler for images stored in an SQL server database. These Images are to be displayed in a gridview on an aspx page.
<%# WebHandler Language="C#" Class="LinqHandler" %>
using System;
using System.Web;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public class LinqHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
SqlConnection connect = new SqlConnection();
connect.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT roomID,roomNumber,roomImage1 FROM Rooms "
+ "WHERE roomID = #roomID";
command.CommandType = System.Data.CommandType.Text;
command.Connection = connect;
SqlParameter RoomID = new SqlParameter("#roomID", System.Data.SqlDbType.Int);
RoomID.Value = context.Request.QueryString["roomID"];
command.Parameters.Add(RoomID);
connect.Open();
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["roomImage1"]);
context.Response.ContentType = "image/gif";
dr.Close();
connect.Close();
}
public bool IsReusable {
get {
return false;
}
}
}
for some reason, the images don't bind to the asp:Image control on the aspx page. I'm stumped as to why.
Here is the databinding snippet:
<asp:GridView ID="GridView1" runat="server"
CssClass="gridviews" PagerStyle-CssClass="pager"
DataKeyNames="roomID" AlternatingRowStyle-CssClass="alt"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="roomID" HeaderText="roomID" />
<asp:BoundField DataField="roomNumber" HeaderText="Room Number" />
<asp:TemplateField HeaderText="Image 1">
<ItemTemplate>
<asp:Image runat="server" ID="pic1"
ImageUrl='<%# "~/LinqHandler.ashx?roomID=" + Eval("roomID") %>'>
</asp:Image>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [roomID], [roomNumber], [roomImage1] FROM [Rooms]">
</asp:SqlDataSource>
you can use Handler.ashx for show image. For example:
<img src="Handler.ashx?roomID=1" />
this way you can show image of the one number room.
If you want to do it another way, you can use base64 in css. You dont need to use handler. For example:
<img runat="server" ID="image"/>
//code behind
var bytes = (byte[])dr["roomImage1"]);
var base64String = System.Convert.ToBase64String(bytes, 0, bytes.Length);
image.src = "data:image/gif;base64,"+ base64String;
EDIT:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var bytes = (byte[])((DataRow)e.Row.DataItem)["roomImage1"];
var base64String = System.Convert.ToBase64String(bytes, 0, bytes.Length);
var image = (Image)e.Row.FindControl("pic1");
image.ImageUrl = "data:image/gif;base64,"+ base64String;
//or
image.ImageUrl = "LinqHandler.ashx?roomID="+((DataRow)e.Row.DataItem)["roomID"];
}
}
Try as below:
<ItemTemplate>
<asp:Image ID="pic1" runat="server"
ImageUrl='<%# Eval("roomID", "LinqHandler.ashx?roomID={0}") %>'
Height="100px" Width="80px" />
</ItemTemplate>
It turns out that my problems stem from inserting garbage into my SQL BLOB fields. There is nothing wrong with the retrieval mechanism posted in my source code. If you are curious to see the insert statements I used, let me know and I will be glad to post them.

SQL Databinding to Dropdown Lists in Repeaters C#

Ok guys, so I am trying to bind data into a dropdown list from c#. I am getting a Null error when trying to enter the data into the DDL's. I am using this code for the front end.
<asp:Repeater ID="RepeaterHardDrives" runat="server">
<HeaderTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hidHardDrivesPackageDefaultID" runat="server" />
<asp:HiddenField ID="hidHardDrivesPackageDefaultPrice" runat="server" />
<span>
<asp:Label runat="server" ID="lbHardDiskPrice" Text="$00.00/mo"></asp:Label></span><label>Hard
Drive:</label><asp:DropDownList ID="ddHardDrive" DataTextField="ItemName" DataValueField="ProductItemID" runat="server" CssClass="lidropdown">
</asp:DropDownList>
<asp:ImageButton runat="server" ID="ShowHarddriveInfo" ImageUrl="/_Images/server_configurator_helpbutton.png"
OnClick="lnkShowHarddriveInfo_OnClick" /></div>
</td>
<td align="right">
<asp:Label runat="server" ID="lbHardDrivesPrice" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<br />
</FooterTemplate>
</asp:Repeater>
for the backend I am trying to load a dynamic number of Dropdown lists into the repeater then databind them all with the same data.
public void PopulateHardDrives(int intSupportedDrives)
{
PreloadHardDriveRepeater(intSupportedDrives);
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connstrname"].ConnectionString);
SqlCommand cmd = new SqlCommand("Prod_SelectIDNamePriceByCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CategoryCode", "Hard Drive");
DataTable dtHardDrives = new DataTable();
using (conn)
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dtHardDrives.Load(dr);
ViewState.Add("dtHardDrives", dtHardDrives);
}
foreach (RepeaterItem riHardDrive in RepeaterHardDrives.Items)
{
DropDownList ddHardDrives = (DropDownList)riHardDrive.FindControl("ddHardDrives");
ddHardDrives.DataSource = dtHardDrives;//program gives NULL exception error here(object not set to instance of object however it know the count of the rows it is supposed to be pulling)
ddHardDrives.DataValueField = "ProductItemID";
ddHardDrives.DataTextField = "ItemName";
ddHardDrives.DataBind();
Label lbHardDrive = (Label)riHardDrive.FindControl("lbHardDrivesPrice");
lbHardDrive.Text = String.Format("{0:c}", Convert.ToDecimal("0.00"));
if (riHardDrive.ItemIndex != 0) //We do not want to allow None to be selected on the main drive
{
ddHardDrives.Items.Insert(0, "None");
}
}
}
and last but not least the function to setup the dynamic amount of DDL's looks like this
private void PreloadHardDriveRepeater(int intSupportedDrives)
{
int[] intArrDisks = new int[intSupportedDrives];
for (int intDiskCount = 0; intDiskCount < intArrDisks.Length; intDiskCount++)
{
intArrDisks[intDiskCount] = intDiskCount;
}
RepeaterHardDrives.DataSource = intArrDisks;
RepeaterHardDrives.DataBind();
}
I am calling a list of populate functions in a !page.isPostBack if statement and the only one that is not getting the data is this one with the Drown Lists. It gets the number of Rows(18) from the database, but it it throwing a Null error(Object reference not set to an instance of an object.) I have seen quite a few people have been running into this error while googling the problem, however I could not find a solution that worked for me. The PreloadHardDriveRepeater function seems to work fine when run alone it loads the correct amount of DDL's onto the page.
Thanks ahead of time.
Your control is "ddHardDrive":
<asp:DropDownList ID="ddHardDrive" DataTextField="ItemName" DataValueField="ProductItemID" runat="server" CssClass="lidropdown">
and your code is looking for "ddHardDrives"
riHardDrive.FindControl("ddHardDrives");
This would be easy to notice if you debugged into the function and looked at your variable values right before the exception is thrown.

Categories

Resources