I want display student information and student image on my web page while selecting student Id from drop down list. Given below code is used for displaying information and image. But the image is not showing properly. Please check the code and out put screen.
Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"].ToString());
TextBox2.Text = (row["SecondName"].ToString());
byte[] barrImg = (byte[])row["StudImage"];
string base6=Convert.ToBase64String(barrImg);
Image1.ImageUrl = "data:image/jpeg;base6," + base6;
}
}
SQL Query:
SELECT FirstName, SecondName, StudentImage FROM TextBoxTable WHERE (Id = #Id)
Aspx Source:
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" />
</div>
Data base:
OutPut:
base64 instead of base6 ???
Image1.ImageUrl = "data:image/jpeg;base64," + base6;
Related
what iam doing is inserting a photo to the database and uploading to the front of my page.
the front page has to show the name and the photo.
iam getting the name from the database and all the photos i have in my UploadedItems folder
here is my front page that has the GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeader="False" Width="325px" OnRowDataBound="gvSearch_RowDataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Text") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField DataImageUrlField="Value" ControlStyle-Height="100" ControlStyle-Width="100" >
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
</Columns>
</asp:GridView>
here is my code:
public partial class ListOfItems : System.Web.UI.Page{
public string ItemImageName, fileName;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
//Response.Redirect("Login.aspx?Data=" + "AddItem");
//Response.Redirect("Login.aspx");
Response.Cookies.Add(new HttpCookie("returnUrl", Request.Url.PathAndQuery));
Response.Redirect("Login.aspx");
}
string[] filePaths = Directory.GetFiles(Server.MapPath("~/UploadedItems/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
fileName = Path.GetFileName(filePath);
DataSet ds = InsertClass.GetItemName(fileName);
foreach (DataRow row in ds.Tables[0].Rows)
{
ItemImageName = row["ItemName"].ToString();
files.Add(new ListItem(ItemImageName, "~/UploadedItems/" + fileName));
//files.Add(new ListItem(ItemImageName, "~/UploadedItems/" + fileName));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("style", "cursor:pointer;");
e.Row.Attributes.Add("onclick", "location='ItemPage.aspx?id=" +ItemImageName+ e.Row.Cells[0].Text + "'");
}
}
}
ok let me explain whats going on in this class first off iam going to the UploadedItems and iam getting every photo in their then iam using their name to query my database with the associated ItemName. now my problem is that when i press the photo it should take me to a page with the ItemName in my gridView that i pressed but what its doing is sending the name of the last picture that was added to the GridView
foreach (DataRow row in ds.Tables[0].Rows) {
ItemImageName = row["ItemName"].ToString();
files.Add(new ListItem(ItemImageName,"~/UploadedItems/" + fileName));
//files.Add(new ListItem(ItemImageName, "~/UploadedItems/" + fileName));
}
Your solution to this problem lies here :-
Each time you are looping inside dataset using datarow your ItemImageName gets a newer value, in final loop you are getting last saved imagename from dataset and it's a global variable you are binding same name for different images in gridview rowdatabound event.
I have drop-down that is not showing the previoiusly selected value in my Detailview. It always shows me the first value in the list. If the previously selected value was xyz then when the Detailvies loads, i want to show xyz. I have researched a lot but could not find any solution that i can use. please help
here is my aspx code for the field that has the dropdown
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label ID="lbl_UID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_Name" Width="200px" Height="25" DataSourceID="SDS_Manager" DataTextField="FULL_NM" AutoPostBack="false"
DataValueField="UID" runat="server" AppendDataBoundItems="false">
<asp:ListItem Text="Select Name" Value="Select Name"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
here is the code behind that binds the detailview
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
sqlcon.Open();
sqlcmd = new SqlCommand(#"Select PRJ_ID, WPC_CD, WPC_DESC, Name FROM myTable where PRJ_ID = '" + myvar + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
DV_Edit.DataSource = dt;
DV_Edit.DataBind();
sqlcon.Close();
popup.Show();
}
}
Try setting AutoPostBack="true" and make sure if you have any logic to set the value of the drop down in the page load, that the code is not executed on post back as shown below.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlOne.DataSource = //your data here;
ddlOne.DataBind();
}
}
//if you don't wrap this logic in the if(!IsPostBack), the code will simply re-populate
//the drop down and set the selected index to the first item in the list with each
//post back.
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'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
I have a repeater with which I want to use to show a user control multiple times, populated with data.
Currently, I have this:
<asp:Repeater runat="server" ID="MyRepeater" >
<ItemTemplate>
<uc1:MyItems ID="MyItems1" runat="server" />
</ItemTemplate>
</asp:Repeater>
My user control has three properties, which I want to populate for each. I currently have this:
protected void Page_Load(object sender, EventArgs e)
{
MyDataSource.SelectCommand =
"SELECT Name, Address, Phone " +
"FROM TestTable ";
MyDataSource.SelectCommandType = SqlDataSourceCommandType.Text;
DataView resultsdv = (DataView)MyDataSource.Select(DataSourceSelectArguments.Empty);
foreach (DataRow dr in resultsdv.Table.Rows)
{
MyItems1.Cust_Name = dr["Name"].ToString();
MyItems1.Cust_Address = dr["Address"].ToString();
MyItems1.Cust_Tel = dr["Phone"].ToString();
}
}
Obviously, this isn’t doing what I want. Is it possible to tell the repeater that I want to populate my user control – either by data binding it, or manually populate it in a way similar to above?
<asp:Repeater runat="server" ID="MyRepeater" >
<ItemTemplate>
<uc1:MyItems ID="MyItems1" MyItems="<%# Eval("Name") %>" ... runat="server" />
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
MyDataSource.SelectCommand =
"SELECT Name, Address, Phone " +
"FROM TestTable ";
MyDataSource.SelectCommandType = SqlDataSourceCommandType.Text;
DataView resultsdv = (DataView)MyDataSource.Select(DataSourceSelectArguments.Empty);
MyRepeater.DataSource = resultsdv.Table.Rows;
MyRepeater.DataBind()
}
I think that needs some corrections:
<asp:Repeater runat="server" ID="MyRepeater" >
<ItemTemplate>
<uc1:MyItems ID="MyItems1" Cust_Name=<%#Eval("Name") %> Cust_Address=<%#Eval("Address")%> Cust_Tel=<%#Eval("Phone")%> runat="server" />
</ItemTemplate>
</asp:Repeater>