ASP.net Display Image from SQL - c#

Solved: I used handlers. Thanks btw.
http://www.aspdotnetcodes.com/Insert_Images_Database.aspx
How can I display my image inside the DataList1?
I don't have a clear idea of databinding and such. I hope you guys can help. Thanks
This is my code for my ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
itemID:
<asp:Label ID="itemIDLabel" runat="server" Text='<%# Eval("itemID") %>' />
<br />
Cloth ID:
<asp:Label ID="Cloth_IDLabel" runat="server" Text='<%# Eval("[Cloth ID]") %>' />
<br />
Style:
<asp:Label ID="StyleLabel" runat="server" Text='<%# Eval("Style") %>' />
<br />
Size:
<asp:Label ID="SizeLabel" runat="server" Text='<%# Eval("Size") %>' />
<br />
Color:
<asp:Label ID="ColorLabel" runat="server" Text='<%# Eval("Color") %>' />
<br />
Image 1:
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("[Image 1]") %>' />
<br />
Image 2:
<asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("[Image 2]") %>' />
<br />
Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />
<br />
Notes:
<asp:Label ID="NotesLabel" runat="server" Text='<%# Eval("Notes") %>' />
<br />
Alignment of Image 1:
<asp:Label ID="Alignment_of_Image_1Label" runat="server"
Text='<%# Eval("[Alignment of Image 1]") %>' />
<br />
Alignment of Image 2:
<asp:Label ID="Alignment_of_Image_2Label" runat="server"
Text='<%# Eval("[Alignment of Image 2]") %>' />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TPSConnectionString %>"
SelectCommand="SELECT CustomizedOrder.userid, CustomizedOrder.itemID, ClothInventory.clothID AS [Cloth ID], ClothInventory.style AS Style, ClothInventory.size AS Size, Color.color AS Color, CustomizedOrder.image1 AS [Image 1], CustomizedOrder.image2 AS [Image 2], CustomizedOrder.itemPrice AS Price, CustomizedOrder.notes AS Notes, Alignment.description AS [Alignment of Image 1], Alignment_1.description AS [Alignment of Image 2] FROM CustomizedOrder INNER JOIN ClothInventory ON CustomizedOrder.clothID = ClothInventory.clothID INNER JOIN Color ON ClothInventory.colorID = Color.colorID INNER JOIN Alignment ON CustomizedOrder.alignment1 = Alignment.alignmentID INNER JOIN Alignment AS Alignment_1 ON CustomizedOrder.alignment2 = Alignment_1.alignmentID WHERE (CustomizedOrder.userid = #userid)">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>
and this is for the aspx.cs
public partial class addtoShoppingCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser User = Membership.GetUser();
object UserGUID = User.ProviderUserKey;
SqlDataSource1.SelectParameters.Add("userid", UserGUID.ToString());
SqlDataSource1.DataBind();
}
}

Asp:Image.ImageUrl expects an URL value, hence if Image1 is a string containing the URL of the image your code should work.
On the contrary, if Image1 is the image itself, then you'll need to temporarily save it on the server and provide the Asp:Image control with the URL for the saved file (check this example for generating the URL)

if you don't have image url from database and you have image datatype in your sql then this code will help to generate image from sql database!

If image path stored in database: ~/Images/file-name.jpg
=> image url in datalist:
ImageUrl='<%# Eval("[ImagePath]") %>' />

Related

how to add txt file contents to textbox

I am receiving the error 'TextBox1 does not exist in this context'
I am new to c# and totally lost as to the problem.
As you can see in my code I would like to use Textbox rather than all the labels.
At present I am working on localhost while testing; not sure if this makes any difference.
My thoughts are the code file is being executed before the Formview has created the controls.
my ASPX file
<%# Page language="C#" masterpagefile="WebBuilder.master" CodeFile="~/Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Bodyhead" ContentPlaceHolderID="BodyHead" runat="server">
<div align="center" style="background-position: center; background-image: url('Images/Rishton-waterfall-Edited.png'); height: 235px; background-repeat: no-repeat; background-color: #FFFFFF; top: 10px;">
</div>
</asp:Content>
<asp:Content ID="NavTop" ContentPlaceHolderID="NavTop" runat="server">
<p align="center" style="font-weight: bold"> <%:DateTime.Now.ToString("ddd, dd MMM yyy HH':'mm':'ss 'GMT'") %></p>
<div align="center">
<asp:Menu ID="Menu3"
runat="server"
Orientation="Horizontal"
RenderingMode="Table"
BackColor="Blue"
ForeColor="Yellow"
Font-Size="14pt"
Width="100%" >
<DynamicHoverStyle ForeColor="Black" Font-Size="16pt" />
<DynamicMenuItemStyle ForeColor="Black" />
<Items>
<asp:MenuItem Text="Home" Value="Home" NavigateUrl="~/Default.aspx"></asp:MenuItem>
<asp:MenuItem Text="Rishton History" Value="Rishton History" NavigateUrl="~/Default.aspx?Page=History"></asp:MenuItem>
<asp:MenuItem Text="Living in Rishton" Value="Living in Rishton" NavigateUrl="">
<asp:MenuItem Text="Streets" Value="Streets" ToolTip="All the streets found in Rishton">
<asp:MenuItem Text="Spring St" Value="Spring St" NavigateUrl="Default.aspx?Page=Spring"></asp:MenuItem>
<asp:MenuItem Text="Livesey St" Value="Livesey St" NavigateUrl="Default.aspx?Page=Livesey"></asp:MenuItem>
<asp:MenuItem Text="High St" Value="High St" NavigateUrl="Default.aspx?Page=High"></asp:MenuItem>
</asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Weather" Value="Weather" NavigateUrl=""></asp:MenuItem>
</Items>
<StaticHoverStyle Font-Size="16pt" ForeColor="Black" />
</asp:Menu>
</div>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="MySiteMap" />
<asp:Menu
ID="Menu2" runat="server" CssClass="menu" Visible="false"
EnableViewState="false" IncludeStyleBlock="false" StaticDisplayLevels="2"
Orientation="Horizontal" DataSourceID="SiteMapDataSource1" >
</asp:Menu>
<asp:SiteMapPath ID="SiteMapPath1" runat="server" SiteMapProvider="MySiteMap" Font-Names="Verdana" Font-Size="14pt" PathSeparator=" > ">
<CurrentNodeStyle ForeColor="Black" />
<NodeStyle Font-Bold="True" ForeColor="Blue" />
<PathSeparatorStyle Font-Bold="True" ForeColor="Red" />
<RootNodeStyle Font-Bold="True" ForeColor="Red" />
</asp:SiteMapPath>
<p align="center" style="border-style: outset">Interactive Website Information Bar</p>
</asp:Content>
<asp:Content ID="Content" ContentPlaceHolderID="Content" runat="server">
<h1 align="center">Rishton</h1>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [AllSite] WHERE ([Keyword] = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="Keyword" QueryStringField="Page" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:FormView runat="server" id="FormView1" DataKeyNames="ID" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<h2><asp:Label id="TitleLabel" runat="server" Text='<%# Bind("Title") %>' /></h2>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server" Text="Test" ></asp:TextBox>
<br />
<asp:Label id="Para1Label" runat="server" Text='<%# Bind("Para1") %>' />
<br /> <br />
<asp:Label id="Label1" runat="server" Text='<%# Bind("Para2") %>' />
<br /> <br />
<asp:Label id="Label2" runat="server" Text='<%# Bind("Para3") %>' />
<br /> <br />
<asp:Label id="Label3" runat="server" Text='<%# Bind("Para4") %>' />
<br /> <br />
<asp:Label id="Label4" runat="server" Text='<%# Bind("Para5") %>' />
<br /> <br />
<asp:Label id="Label5" runat="server" Text='<%# Bind("Para6") %>' />
<br /> <br />
<asp:Label id="Label6" runat="server" Text='<%# Bind("Para7") %>' />
<br /> <br />
<asp:Label id="Label7" runat="server" Text='<%# Bind("Para8") %>' />
<br /> <br />
<asp:Label id="Label10" runat="server" Text='<%# Bind("Para9") %>' />
<br /> <br />
<asp:Label id="Label11" runat="server" Text='<%# Bind("Para10") %>' />
<br /> <br />
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("ImageLink") %>' Width="640px" Height="320px" />
<br /> <br />
</ItemTemplate>
</asp:FormView>
</asp:Content>
<asp:Content ID="Footer" ContentPlaceHolderID="Foot" runat="server">
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [AllSite] WHERE ([Keyword] = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="Keyword" QueryStringField="Page" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<h1>References</h1>
<asp:FormView runat="server" id="FormView2" DataKeyNames="ID" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:Label id="Refs1" runat="server" Text='<%# Bind("Refs1") %>' />
<br /> <br />
<asp:Label id="Refs2" runat="server" Text='<%# Bind("Refs2") %>' />
<br /> <br />
<asp:Label id="Refs3" runat="server" Text='<%# Bind("Refs3") %>' />
<br /> <br />
<asp:Label id="Refs4" runat="server" Text='<%# Bind("Refs4") %>' />
<br /> <br />
<asp:Label id="Refs5" runat="server" Text='<%# Bind("Refs5") %>' />
<br /> <br />
<asp:Label id="Refs6" runat="server" Text='<%# Bind("Refs6") %>' />
<br /> <br />
<asp:Label id="Refs7" runat="server" Text='<%# Bind("Refs7") %>' />
<br /> <br />
<asp:Label id="Refs8" runat="server" Text='<%# Bind("Refs8") %>' />
<br /> <br />
<asp:Label id="Refs9" runat="server" Text='<%# Bind("Refs9") %>' />
<br /> <br />
<asp:Label id="Refs10" runat="server" Text='<%# Bind("Refs10") %>' />
<br />
</ItemTemplate>
</asp:FormView>
<p align="center">© <%: DateTime.Now.Year %> - Website Builder Ver 1.0 </p>
</asp:Content>
my aspx.cs file
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void btn_Click(object sender, EventArgs e,)
{
string txt = File.ReadAllText(Server.MapPath("~/Text/RishtonHistory.txt"));
TextBox1 = txt;
}
}
Thanks in advance for any help.
You should access to FormView1 then its children named TextBox1. You can access like this
string txt = File.ReadAllText(Server.MapPath("~/Text/RishtonHistory.txt"));
//TextBox1 = txt;
TextBox textBox1 = ((TextBox)FormView1.FindControl("TextBox1"));
textBox1.Text = txt;
It does not matter your are on localhost or server.

Updatepage | Why does my image field in db get overwritten with null value when I update?

I'm new to coding, so sorry if some of my jargon is wrong.
I'm trying to make an update page that will update database values. All other fields update fine, however whenever I attempt to update the database without an image upload, it will replace the current field value with a null value. Any help would be appreciated to remedy this issue. Exact code would be excellent, as I said before I'm new to coding, especially asp.net and C# so some terms are new to me.
Below is my code behind file, I imagine this is the cause of my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class admin_updatenews : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void displayedit_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
info.Text = "Item Updated";
FileUpload fileupdate = displayedit.EditItem.FindControl("imageupdate") as FileUpload;
Label recordid = displayedit.EditItem.FindControl("idlabel1") as Label;
Int32 id = Convert.ToInt32(recordid.Text);
if (fileupdate.HasFile)
{
String fupload = fileupdate.FileName;
Random r = new Random();
int rInt = r.Next(0, 10000);
String imgpath = "../images/" + rInt + fupload;
fileupdate.SaveAs(Server.MapPath(imgpath));
String newimage = rInt + fupload;
string newsconnection = WebConfigurationManager.ConnectionStrings["newsconnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(newsconnection);
//myConnection.ConnectionString is now set to connectionString.
myConnection.Open();
String query = "UPDATE News SET postimage ='" + newimage + "', Image ='" + newimage + "' WHERE id='" + id + "'";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
protected void displayedit_ItemEditing(object sender, ListViewEditEventArgs e)
{
info.Text = "I am editing";
}
protected void displayedit_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
info.Text = "Not Updating";
}
}
This is the front end code in case that is required
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Copy of updatenews.aspx.cs" Inherits="admin_updatenews" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="../css/responsive.css" rel='stylesheet' type='text/css' />
<link href="../css/gui.css" rel='stylesheet' type='text/css' />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="newseditrows" runat="server"
ConnectionString='<%$ ConnectionStrings:newsconnection %>'
SelectCommand="SELECT News.id, News.headline, News.Image, News.paragraph, Sportslist.sportname, News.Sport, News.date, News.lead, News.authorID, Sportslist.id, News.postheadline, News.postimage, News.postparagraph, News.postsport, News.postdate, News.postlead, News.postauthorid
FROM News
INNER JOIN Sportslist ON News.Sport = Sportslist.id
ORDER BY News.id DESC"
UpdateCommand="UPDATE [News] SET [headline]=#headline, [Image]=#Image, [paragraph]=#paragraph, [Sport]=#sport, [date]=#date, [lead]=#lead, [authorid]=#authorid, [postheadline]=#headline, [postimage]=#Image, [postparagraph]=#paragraph, [postsport]=#sport, [postdate]=#date, [postlead]=#lead, [postauthorid]=#authorid WHERE [id]=#id">
<UpdateParameters>
<asp:Parameter Name="headline" Type="String" />
<asp:Parameter Name="Image" Type="String" />
<asp:Parameter Name="paragraph" Type="String" />
<asp:Parameter Name="Sport" Type="Int32" />
<asp:Parameter Name="date" Type="DateTime" />
<asp:Parameter Name="lead" Type="String" />
<asp:Parameter Name="authorid" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sportlist" runat="server"
ConnectionString='<%$ ConnectionStrings:newsconnection %>'
SelectCommand="SELECT [id], [sportname] FROM [Sportslist]">
</asp:SqlDataSource>
<asp:Label ID="info" runat="server" Text="Not Updating"></asp:Label>
<br />
<asp:ListView ID="displayedit" runat="server"
DataSourceID="newseditrows"
DataKeyNames="id"
OnItemUpdated="displayedit_ItemUpdated"
OnItemEditing="displayedit_ItemEditing"
OnItemCanceling="displayedit_ItemCanceling">
<AlternatingItemTemplate>
<span style="">id:
<asp:Label Text='<%# Eval("id") %>' runat="server" ID="idLabel" /><br />
headline:
<asp:Label Text='<%# Eval("headline") %>' runat="server" ID="headlineLabel" /><br />
Image:
<asp:Image ID="ImageLabel" runat="server" ImageURL='<%# "../images/" + Eval("Image") %>' Width="100px" />
<br />
paragraph:
<asp:Label Text='<%# Eval("paragraph") %>' runat="server" ID="paragraphLabel" /><br />
Sport:
<asp:Label Text='<%# Eval("sportname") %>' runat="server" ID="SportLabel" /><br />
date:
<asp:Label Text='<%# Eval("date") %>' runat="server" ID="dateLabel" /><br />
lead:
<asp:Label Text='<%# Eval("lead") %>' runat="server" ID="leadLabel" /><br />
authorID:
<asp:Label Text='<%# Eval("authorID") %>' runat="server" ID="authorIDLabel" /><br />
<asp:Button runat="server" CommandName="Edit" Text="Edit" ID="EditButton" />
<br />
<br />
</span>
</AlternatingItemTemplate>
<EditItemTemplate>
<span style="">id:
<asp:Label Text='<%# Eval("id") %>' runat="server" ID="idLabel1" /><br />
headline:
<asp:TextBox Text='<%# Bind("headline") %>' runat="server" ID="headlineTextBox" /><br />
Image:
<asp:Image ID="ImageTextBox1" runat="server" ImageUrl='<%# "../images/" + Eval("Image") %>' Width="100px"/>
<asp:FileUpload ID="imageupdate" runat="server" />
<br />
paragraph:
<asp:TextBox Text='<%# Bind("paragraph") %>' runat="server" ID="paragraphTextBox" /><br />
Sport:
<%--<asp:TextBox Text='<%# Bind("Sport") %>' runat="server" ID="SportTextBox" />--%>
<asp:DropDownList ID="SportsDropdown" runat="server" SelectedValue='<%# Bind("Sport") %>'>
<asp:ListItem Value="1">Football</asp:ListItem>
<asp:ListItem Value="2">Rugby</asp:ListItem>
<asp:ListItem Value="3">Basketball</asp:ListItem>
<asp:ListItem Value="4">Motorsport</asp:ListItem>
<asp:ListItem Value="5">NFL</asp:ListItem>
<asp:ListItem Value="6">Cricket</asp:ListItem>
<asp:ListItem Value="7">Tennis</asp:ListItem>
<asp:ListItem Value="8">Golf</asp:ListItem>
<asp:ListItem Value="9">Other</asp:ListItem>
</asp:DropDownList>
<br />
lead:
<asp:TextBox Text='<%# Bind("lead") %>' runat="server" ID="leadTextBox" /><br />
<asp:Button runat="server" CommandName="Update" Text="Update" ID="UpdateButton" /><asp:Button runat="server" CommandName="Cancel" Text="Cancel" ID="CancelButton" /><br />
<br />
</span>
</EditItemTemplate>
<EmptyDataTemplate>
<span>No data was returned.</span>
</EmptyDataTemplate>
<InsertItemTemplate>
<span style="">headline:
<asp:TextBox Text='<%# Bind("headline") %>' runat="server" ID="headlineTextBox" /><br />
Image:
<asp:TextBox Text='<%# Bind("Image") %>' runat="server" ID="ImageTextBox" /><br />
paragraph:
<asp:TextBox Text='<%# Bind("paragraph") %>' runat="server" ID="paragraphTextBox" /><br />
Sport:
<asp:TextBox Text='<%# Bind("Sport") %>' runat="server" ID="SportTextBox" /><br />
date:
<asp:TextBox Text='<%# Bind("date") %>' runat="server" ID="dateTextBox" /><br />
lead:
<asp:TextBox Text='<%# Bind("lead") %>' runat="server" ID="leadTextBox" /><br />
authorID:
<asp:TextBox Text='<%# Bind("authorID") %>' runat="server" ID="authorIDTextBox" /><br />
<asp:Button runat="server" CommandName="Insert" Text="Insert" ID="InsertButton" /><asp:Button runat="server" CommandName="Cancel" Text="Clear" ID="CancelButton" /><br />
<br />
</span>
</InsertItemTemplate>
<ItemTemplate>
<span style="">id:
<asp:Label Text='<%# Eval("id") %>' runat="server" ID="idLabel" /><br />
headline:
<asp:Label Text='<%# Eval("headline") %>' runat="server" ID="headlineLabel" /><br />
Image:
<asp:Image ID="ImageLabel" runat="server" ImageURL='<%# "../images/" + Eval("Image") %>' Width="100px" />
<br />
paragraph:
<asp:Label Text='<%# Eval("paragraph") %>' runat="server" ID="paragraphLabel" /><br />
Sport:
<asp:Label Text='<%# Eval("sportname") %>' runat="server" ID="SportLabel" /><br />
date:
<asp:Label Text='<%# Eval("date") %>' runat="server" ID="dateLabel" /><br />
lead:
<asp:Label Text='<%# Eval("lead") %>' runat="server" ID="leadLabel" /><br />
authorID:
<asp:Label Text='<%# Eval("authorID") %>' runat="server" ID="authorIDLabel" /><br />
<asp:Button runat="server" CommandName="Edit" Text="Edit" ID="EditButton" />
<br />
<br />
</span>
</ItemTemplate>
<LayoutTemplate>
<div runat="server" id="itemPlaceholderContainer" style=""><span runat="server" id="itemPlaceholder" /></div>
<div style="">
<asp:DataPager runat="server" ID="DataPager1">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False"></asp:NextPreviousPagerField>
<asp:NumericPagerField></asp:NumericPagerField>
<asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False"></asp:NextPreviousPagerField>
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
<SelectedItemTemplate>
<span style="">id:
<asp:Label Text='<%# Eval("id") %>' runat="server" ID="idLabel" /><br />
headline:
<asp:Label Text='<%# Eval("headline") %>' runat="server" ID="headlineLabel" /><br />
Image:
<asp:Label Text='<%# Eval("Image") %>' runat="server" ID="ImageLabel" /><br />
paragraph:
<asp:Label Text='<%# Eval("paragraph") %>' runat="server" ID="paragraphLabel" /><br />
Sport:
<asp:Label Text='<%# Eval("Sport") %>' runat="server" ID="SportLabel" /><br />
date:
<asp:Label Text='<%# Eval("date") %>' runat="server" ID="dateLabel" /><br />
lead:
<asp:Label Text='<%# Eval("lead") %>' runat="server" ID="leadLabel" /><br />
authorID:
<asp:Label Text='<%# Eval("authorID") %>' runat="server" ID="authorIDLabel" /><br />
<asp:Button runat="server" CommandName="Edit" Text="Edit" ID="EditButton" />
<br />
<br />
</span>
</SelectedItemTemplate>
</asp:ListView>
</div>
</form>
</body>
</html>
Here is example of the update statement using ur query.
UPDATE News
SET postimage = ISNULL(YourNewValue, postimage), Image = ISNULL(YourNewValue, Image)
WHERE id = YourID
EDIT :
try adding following in your datasource updateCommand. if this doesn't solve than try stepping through to see where this is adding null.
UpdateCommand="UPDATE [News] SET [headline]=#headline, [Image]= ISNULL(#Image, [Image]), [paragraph]=#paragraph, [Sport]=#sport, [date]=#date, [lead]=#lead, [authorid]=#authorid, [postheadline]=#headline, [postimage]=#Image, [postparagraph]=#paragraph, [postsport]=#sport, [postdate]=#date, [postlead]=#lead, [postauthorid]=#authorid WHERE [id]=#id">

My e.CommandArgument is returning "" Every Time

Whenever I click one of the delete linkbuttons, the e.CommandArgument always retains the value of "". I was reading somewhere that you can't use <%# in Command Arguments but I have seen several examples were this has worked. Any suggestions?
In ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:Label ID="dataLabel" runat="server" Text='<%# Eval("data") %>' />
<br />
<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
|
<asp:Label ID="Column1Label" runat="server" Text='<%# Eval("Column1") %>' />
<br />
<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<LoggedInTemplate>
<asp:LinkButton CLASS="DeleteButton" runat="server" OnCommand="Delete" CommandArgument='<%# Eval("id") %>' ViewStateMode="Disabled">Delete</asp:LinkButton>
</LoggedInTemplate>
</asp:LoginView>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [id],[name], [data], convert(varchar, [date], 101) FROM [Announcements] ORDER BY [date] DESC">
</asp:SqlDataSource>
IN ASPX.CS
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
SqlCommand command = conn.CreateCommand();
command.CommandText = "DELETE FROM Annoucnements WHERE id=#id";
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add(new SqlParameter("id", e.CommandArgument));
conn.Open();
command.ExecuteNonQuery();
}
As suggested by Royi Namir, changing EnableViewState to true fixed the problem.
After looking around for a little bit, I have found a few posts that say you can't use the <%# ... %> syntax inside server tags, which is clearly wrong as you are using it for the Text property and I'm sure I've done this exact same thing before. Anyway, you can use the ItemDataBound event on your DataList:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<asp:Label ID="dataLabel" runat="server" Text='<%# Eval("data") %>' />
<br />
<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
|
<asp:Label ID="Column1Label" runat="server" Text='<%# Eval("Column1") %>' />
<br />
<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<LoggedInTemplate>
<asp:LinkButton CssClass="DeleteButton" runat="server" ID="lbDelete" OnCommand="Delete" CommandArgument='<%# Eval("id") %>' ViewStateMode="Disabled">Delete</asp:LinkButton>
</LoggedInTemplate>
</asp:LoginView>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [id],[name], [data], convert(varchar, [date], 101) FROM [Announcements] ORDER BY [date] DESC">
</asp:SqlDataSource>
Notice I've added ID="lbDelete" to your LinkButton (and also changed CLASS to CssClass for you) which is needed to find the control in our code behind:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) // this is to ensure that we're looking in an item that will contain controls, and not the header or footer
{
LoginView headLoginView = (LoginView)e.Item.FindControl("HeadLoginView") // FindControl is not recursive so we need a reference to a control we can look in to find the button
LinkButton lbDelete = (LinkButton)headLoginView.FindControl("lbDelete");
if (lbDelete != null) // check for a null otherwise this code will fail if the user is not logged in, because the controls inside the LoggedInTemplate will not be rendered
{
lbDelete.CommandArgument = DataBinder.Eval(e.Item.DataItem, "id").ToString(); // set the CommandArgument on the button using DataBinder.Eval
}
}
}
You simply need the DataKeyField to uniquely identify your row in order to perform Delete operations.

An SqlParameter with ParameterName '#UserId' is not contained by this SqlParameterCollection

I had a login page. once user successfuly logged in, they can view and manage their profile/information. This would be done by retrieving data from database and display on a formview.
However this following error appeared inside my userprofile.aspx.cs file:
Exception Details: System.IndexOutOfRangeException: An SqlParameter with ParameterName '#UserId' is not contained by this SqlParameterCollection.
Source Error:
Line 44:
Line 45: // Assign the currently logged on user's UserId to the #UserId parameter
Line 46: e.Command.Parameters["#UserId"].Value = currentUserId;
Line 47:
Line 48: }
Userprofile.aspx:
<asp:FormView ID="FormView1" runat="server"
DataSourceID="SqlDataSource1" DataKeyNames="UserId">
<EditItemTemplate>
UserId:
<asp:Label ID="UserIdLabel1" runat="server" Text='<%# Eval("UserId") %>' />
<br />
Password:
<asp:TextBox ID="PasswordTextBox" runat="server"
Text='<%# Bind("Password") %>' />
<br />
Email:
<asp:TextBox ID="EmailTextBox" runat="server" Text='<%# Bind("Email") %>' />
<br />
HomeTown:
<asp:TextBox ID="HomeTownTextBox" runat="server"
Text='<%# Bind("HomeTown") %>' />
<br />
HomepageUrl:
<asp:TextBox ID="HomepageUrlTextBox" runat="server"
Text='<%# Bind("HomepageUrl") %>' />
<br />
Signature:
<asp:TextBox ID="SignatureTextBox" runat="server"
Text='<%# Bind("Signature") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
UserId:
<asp:TextBox ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
<br />
Password:
<asp:TextBox ID="PasswordTextBox" runat="server"
Text='<%# Bind("Password") %>' />
<br />
Email:
<asp:TextBox ID="EmailTextBox" runat="server" Text='<%# Bind("Email") %>' />
<br />
HomeTown:
<asp:TextBox ID="HomeTownTextBox" runat="server"
Text='<%# Bind("HomeTown") %>' />
<br />
HomepageUrl:
<asp:TextBox ID="HomepageUrlTextBox" runat="server"
Text='<%# Bind("HomepageUrl") %>' />
<br />
Signature:
<asp:TextBox ID="SignatureTextBox" runat="server"
Text='<%# Bind("Signature") %>' />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
UserId:
<asp:Label ID="UserIdLabel" runat="server" Text='<%# Eval("UserId") %>' />
<br />
Password:
<asp:Label ID="PasswordLabel" runat="server" Text='<%# Bind("Password") %>' />
<br />
Email:
<asp:Label ID="EmailLabel" runat="server" Text='<%# Bind("Email") %>' />
<br />
HomeTown:
<asp:Label ID="HomeTownLabel" runat="server" Text='<%# Bind("HomeTown") %>' />
<br />
HomepageUrl:
<asp:Label ID="HomepageUrlLabel" runat="server"
Text='<%# Bind("HomepageUrl") %>' />
<br />
Signature:
<asp:Label ID="SignatureLabel" runat="server" Text='<%# Bind("Signature") %>' />
<br />
</ItemTemplate>
</asp:FormView>
</p>
<p>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SecurityTutorialsConnectionString %>"
onselecting="SqlDataSource1_Selecting"
SelectCommand="SELECT UserProfiles.UserId, aspnet_Membership.Password, aspnet_Membership.Email, UserProfiles.HomeTown, UserProfiles.HomepageUrl, UserProfiles.Signature FROM aspnet_Membership INNER JOIN UserProfiles ON aspnet_Membership.UserId = UserProfiles.UserId">
</asp:SqlDataSource>
</p>
<p>
</p>
</asp:Content>
Userprofile.aspx.cs:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
// Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Assign the currently logged on user's UserId to the #UserId parameter
e.Command.Parameters["#UserId"].Value = currentUserId;
}
Create a new SqlParameter and add it to the collection.
SqlParameter param = new SqlParameter("#UserId", currentUserId);
e.Command.Parameters.Add(param);
Try the following:
DbParameter param = e.Command.CreateParameter();
param.ParameterName = "#UserId";
param.Value = currentUserId;
e.Command.Parameters.Add(param);
I didn't test this though
You must add the parameter with
e.Command.Parameters.AddWithValue("#UserId", currentUserId);
Once you have added it you could access it through the indexer as in your example.
UPDATE
If you are working with the System.Data.Common namespace, the AddWithValue method is not available. You will have to do something like
var param = e.Command.CreateParameter("#UserId", currentUserId);
e.Command.Parameters.Add(param);
This is a little bit more complicated but has the advantage that you do not have to implicitly create a parameter of a specific type like SqlParamter or OleDbParameter.
If you already have the parameter listed in your SqlDataSource, then simply point to it and change it's value ...
e.Command.Parameters["#UserId"].Value = currentUserId;
You do not need to create a parameter, unless you have not listed it back in your ASP page.

DataBinding problem

I have a DataList Control as follows
<asp:DataList ID="DataList1" runat="server" DataKeyField="FruitID" RepeatColumns="2" Width="387px">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="104px" ImageUrl='<%# Eval("ImageUrl") %>' Width="135px" />
<br />
Item ID:
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("FruitID") %>' />
<br />
FruitName:
<asp:Label ID="lblFruitNameLabel" runat="server" Text='<%# Eval("FruitName") %>' />
<br />
UnitPrice:
<asp:Label ID="lblUnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />
<br />
Quantity:
<asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:Button ID="btnAddtoCart" runat="server" onclick="Button1_Click" Text="Add to Cart" />
and in the code behind im using the following code to get the values of the controls inside the DataList control
int id = int.Parse(((Label)DataList1.Controls[0].FindControl("lblItemID")).Text.ToString());
string Name = ((Label)DataList1.Controls[0].FindControl("lblFruitNameLabel")).Text;
double Price = double.Parse(((Label)DataList1.Controls[0].FindControl("lblUnitPriceLabel")).Text.ToString());
int Quantity = int.Parse(((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString());
string Url = ((Image)DataList1.Controls[0].FindControl("Image1")).ImageUrl;
I'm getting the following exception
Input string was not in a correct format.
Exception occurs in the following line
int Quantity = int.Parse(((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString());
I'm very much sure that i'm entering a Integer value to the textbox :)
am I missing something?
Maybe that would be great when you little bit rewrite your code to this
var myQuantity = ((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString();
int Quantity = int.Parse(myQuantity);
and check with Debugger what type is myQuantity. This should help you to locate your issue.
It could be because of the type casting problem, from the number you entered, to integer. Try making it a long data type instead and also make sure that no characters exists in between the string you entered.
try this
int Quantity =Convert.ToInt32(((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString());
<br />
Quantity :
<asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
<br />
i saw that u have not make any bind to txtQuantity. And Convert.ToInt32 gives exception because it s null string. i think so

Categories

Resources