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.
Related
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.
I'm attempting to insert a value into TextBoxes in a ListView according to the user id label value of the student in the ListView. In the front end there is a textbox for each student listed to type in a grade for. Below is part of my code I have written to attempt to find the TextBox Control, retrieve results that are already there and assign to the TextBoxes matching the correct student:
<div class="col-sm-12">
<div class="row moduleDrop">
<h2>Final module results</h2>
<h4>Select the degree programme:</h4>
<asp:Label ID="degreeProgValue" runat="server"></asp:Label>
<br />
<asp:SqlDataSource ID="degreeSelect" runat="server" ConnectionString="<%$ ConnectionStrings:UniString %>"
SelectCommand="SELECT pathway_years.id, (pathway_year + ' ' + pathway ) AS pathwayDetails FROM pathways INNER JOIN pathway_years ON pathways.id = pathway_years.pathway_id"></asp:SqlDataSource>
<asp:DropDownList ID="degreeProgDropDown" runat="server" Width="420" AutoPostBack="true"
DataSourceID="degreeSelect" DataTextField="pathwayDetails" DataValueField="id">
</asp:DropDownList>
</div>
</div>
<div class="col-sm-12">
<div class="row moduleDrop">
<h4>Select module:</h4>
<asp:Label ID="TBTest" runat="server" Visible="true"></asp:Label>
<br />
<asp:SqlDataSource ID="modSource" runat="server" ConnectionString="<%$ ConnectionStrings:UniString %>"
SelectCommand="SELECT DISTINCT module_on_pathway.module_id, modules.module_name FROM modules INNER JOIN module_on_pathway ON modules.id = module_on_pathway.module_id INNER JOIN pathway_years ON module_on_pathway.pathway_year_id = pathway_years.id INNER JOIN class ON pathway_years.id = class.pathway_year_id INNER JOIN classlist ON class.class_id = classlist.class_id INNER JOIN users ON classlist.user_id = users.id WHERE mandatory_module = 1 AND pathway_years.id = #pwayYearid UNION SELECT module_on_pathway.id, modules.module_name FROM modules INNER JOIN module_on_pathway ON modules.id = module_on_pathway.module_id INNER JOIN pathway_years ON module_on_pathway.pathway_year_id = pathway_years.id INNER JOIN class ON pathway_years.id = class.pathway_year_id INNER JOIN classlist ON class.class_id = classlist.class_id INNER JOIN chosen_modules_list ON classlist.classlist_id = chosen_modules_list.classlist_id INNER JOIN users ON classlist.user_id = users.id WHERE chosen_modules_list.module_on_pathway_id = module_on_pathway.id AND pathway_years.id = #pwayYearid">
<SelectParameters>
<asp:ControlParameter ControlID="degreeProgDropDown" Name="pwayYearid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="modDropDown" runat="server" Width="420" AutoPostBack="true" EnableViewState="true"
DataSourceID="modSource" DataTextField="module_name" DataValueField="module_id">
</asp:DropDownList>
</div>
<br />
</div>
<div class="classList">
<h4>Select the student:</h4>
<br />
<asp:SqlDataSource ID="SQLStudentList" runat="server" ConnectionString="<%$ ConnectionStrings:UniString %>"
SelectCommand="SELECT students_profile.user_id, first_name, last_name FROM classlist
INNER JOIN students_profile ON classlist.user_id = students_profile.user_id
INNER JOIN class ON classlist.class_id = class.class_id
INNER JOIN pathway_years ON class.pathway_year_id = #pwayYearid
INNER JOIN module_on_pathway ON pathway_years.id = module_on_pathway.pathway_year_id
WHERE module_on_pathway.mandatory_module = 1
AND module_on_pathway.module_id = #modpwayid
UNION
SELECT students_profile.user_id, first_name, last_name FROM classlist
INNER JOIN students_profile ON classlist.user_id = students_profile.user_id
INNER JOIN class ON classlist.class_id = class.class_id
INNER JOIN pathway_years ON class.pathway_year_id = #pwayYearid
INNER JOIN module_on_pathway ON pathway_years.id = module_on_pathway.pathway_year_id
INNER JOIN chosen_modules_list ON classlist.classlist_id = chosen_modules_list.classlist_id
WHERE chosen_modules_list.module_on_pathway_id = module_on_pathway.id
AND module_on_pathway.module_id = #modpwayid">
<SelectParameters>
<asp:ControlParameter ControlID="degreeProgDropDown" Name="pwayYearid" />
<asp:ControlParameter Name="modpwayid" ControlID="modDropDown" />
</SelectParameters>
</asp:SqlDataSource>
<asp:ListView runat="server" OnItemDataBound="studentsListView_ItemDataBound" ID="studentsListView" DataSourceID="SQLStudentList">
<AlternatingItemTemplate>
<strong><span style="">Student Number:</strong>
<asp:Label ID="user_idLabel" runat="server" Text='<%# Eval("user_id") %>' />
<br />
<strong>Name:</strong>
<asp:Label ID="first_nameLabel" runat="server" Text='<%# Eval("first_name") %>' />
<asp:Label ID="last_nameLabel" runat="server" Text='<%# Eval("last_name") %>' />
<br />
<asp:TextBox ID="finalMarkAssignment" runat="server" Width="40"></asp:TextBox>
<asp:Label ID="gradeForStudent" runat="server" Visible="false"></asp:Label>
<br />
<br />
<asp:Button CssClass="btn btn-success" ID="submitModuleMark" OnClientClick="ShowLabel();" runat="server" Text="Submit Grade" OnClick="submitModuleMark_Click" />
<br />
<asp:Button CssClass="btn btn-success" ID="repeatSubmitModuleMark" OnClientClick="ShowLabel();" runat="server" Text="Submit repeat module grade" OnClick="repeatSubmitModuleMark_Click" />
<br />
<br />
</span>
</AlternatingItemTemplate>
<EditItemTemplate>
<span style="">user_id:
<asp:TextBox ID="user_idTextBox" runat="server" Text='<%# Bind("user_id") %>' />
<br />
first_name:
<asp:TextBox ID="first_nameTextBox" runat="server" Text='<%# Bind("first_name") %>' />
<br />
last_name:
<asp:TextBox ID="last_nameTextBox" runat="server" Text='<%# Bind("last_name") %>' />
<br />
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
<br />
<br />
</span>
</EditItemTemplate>
<EmptyDataTemplate>
<span>No data was returned.</span>
</EmptyDataTemplate>
<InsertItemTemplate>
<span style="">user_id:
<asp:TextBox ID="user_idTextBox" runat="server" Text='<%# Bind("user_id") %>' />
<br />
first_name:
<asp:TextBox ID="first_nameTextBox" runat="server" Text='<%# Bind("first_name") %>' />
<br />
last_name:
<asp:TextBox ID="last_nameTextBox" runat="server" Text='<%# Bind("last_name") %>' />
<br />
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
<br />
<br />
</span>
</InsertItemTemplate>
<ItemTemplate>
<span style="">
<strong>Student Number:</strong>
<asp:Label ID="user_idLabel" runat="server" Text='<%# Eval("user_id") %>' />
<br />
<strong>Name:</strong>
<asp:Label ID="first_nameLabel" runat="server" Text='<%# Eval("first_name") %>' />
<asp:Label ID="last_nameLabel" runat="server" Text='<%# Eval("last_name") %>' />
<br />
<asp:TextBox ID="finalMarkAssignment" runat="server" Width="40"></asp:TextBox>
<br />
<br />
<asp:Button CssClass="btn btn-success" ID="submitModuleMark" OnClientClick="ShowLabel();" runat="server" Text="Submit Grade" OnClick="submitModuleMark_Click" />
<br />
<asp:Button CssClass="btn btn-success" ID="repeatSubmitModuleMark" OnClientClick="ShowLabel();" runat="server" Text="Submit repeat module grade" OnClick="repeatSubmitModuleMark_Click" />
<br />
<br />
</span>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<span runat="server" id="itemPlaceholder" />
</div>
<div style="">
</div>
</LayoutTemplate>
<SelectedItemTemplate>
<span style="">user_id:
<asp:Label ID="user_idLabel" runat="server" Text='<%# Eval("user_id") %>' />
<br />
first_name:
<asp:Label ID="first_nameLabel" runat="server" Text='<%# Eval("first_name") %>' />
<br />
last_name:
<asp:Label ID="last_nameLabel" runat="server" Text='<%# Eval("last_name") %>' />
<br />
<br />
</span>
</SelectedItemTemplate>
</asp:ListView>
</div>
<div class="col-sm-12">
<br />
<asp:Label ID="changedFlag" runat="server" Visible="false"></asp:Label>
<asp:Label ID="assignmentIDValue" runat="server" Visible="false"></asp:Label>
<asp:Label ID="pOrF" runat="server" Visible="false"></asp:Label>
<asp:Label ID="EnterFinalMark" runat="server" Visible="false">Enter a final mark for this module</asp:Label>
<br />
<asp:Label ID="success" runat="server" Visible="false" Text="Grade has been changed successfully"></asp:Label>
<asp:Label ID="changedVAL" Visible="false" runat="server"></asp:Label>
</div>
</div>
When you put a breakpoint on TextBox TB does it have a value when you step into it?
I suspect that you haven't put this code within a method that fires on data binding for the listview items, and you need to. If you put it elsewhere (eg on page load), it won't be able to find the individual text boxes.
First you need to subscribe to the ItemDataBound event of the ListView in your page load code. You can either do this declaratively in your front-end code
<asp:ListView ID="studentsListView" OnItemDataBound="listView_OnItemDataBound" runat="server"></asp:ListView>
Or you can do it in the page load in the back end code
studentsListView.ItemDataBound += listView_OnItemDataBound();
And then for each item, you can do something with it
protected void listView_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
// get the button or any other control on the current row
TextBox tB = (TextBox) e.Item.FindControl("finalMarkAssignment");
if(tb != null)
{
// do something
}
}
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">
<asp:Panel ID="pnlGrdShift" runat="server" ScrollBars="Auto" Width="900px" Height="520px" CssClass="srcColor">
<cc1:GridView ID="gvShift" runat="server" AutoGenerateColumns="False" AllowSorting="True"
CssClass="grid"
OnDataBound="gvShift_DataBound"
DataSourceID="odsShiftDetails"
AllowPaging="True"
ShowFooter="false"
onrowcancelingedit="gvShift_RowCancelingEdit"
onrowcommand="gvShift_RowCommand"
onrowdeleting="gvShift_RowDeleting"
onrowediting="gvShift_RowEditing"
onrowupdating="gvShift_RowUpdating"
OnSelectedIndexChanged="gvShift_SelectedIndexChanged"
OnRowDataBound="gvShift_RowDataBound">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" Wrap="false" />
<EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
<EmptyDataTemplate >
No Records Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="E Code" SortExpression="userecode" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserECode" runat="server" Text='<%#Eval("userecode") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserECode" runat="server" Text='<%#Eval("userecode") %>' style="width:50px;" CssClass="GridContent" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Name" SortExpression="username" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("username") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserName" runat="server" Text='<%#Eval("username") %>' style="width:100px;" CssClass="GridContent"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift Start Time" SortExpression="ShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftStartTime" runat="server" ControlToValidate="ddlShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift End Time" SortExpression="ShiftEndTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftEndTime" runat="server" ControlToValidate="ddlShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="ShiftEndTIme" HeaderText="Shift End Time" SortExpression="ShiftEndTIme"/>--%>
<asp:TemplateField HeaderText="Saturday Shift Start Time" SortExpression="WeekendShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftStartTime" runat="server" ControlToValidate="ddlWeekendShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saturday Shift End Time" SortExpression="weekendshiftendtime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftEndTime" runat="server" ControlToValidate="ddlWeekendShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ForeColor="White"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ForeColor="White"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate >
<table width="100%" >
<tr>
<td style="text-align: left">
Page Size:
<asp:DropDownList ID="ddPageSize" runat="server" EnableViewState="true" OnSelectedIndexChanged="ddPageSize_SelectedIndexChanged" AutoPostBack="true" style="width:50px;">
<asp:ListItem Text="10" ></asp:ListItem>
<asp:ListItem Text="20" ></asp:ListItem>
<asp:ListItem Text="30" ></asp:ListItem>
<asp:ListItem Text="40" ></asp:ListItem>
<asp:ListItem Text="50" ></asp:ListItem>
</asp:DropDownList>
</td>
<td style="text-align: right">
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
</td>
</tr>
</table>
</PagerTemplate>
</cc1:GridView>
</asp:Panel></td></tr>
</table>
<div style="margin-top:5px" class="PagerGrid">
<asp:DataPager ID="pager" runat="server" PagedControlID="gvShift">
<Fields>
<asp:NextPreviousPagerField FirstPageText="<<" LastPageText=">>"
NextPageText=">" PreviousPageText="<" ShowFirstPageButton="True"
ShowNextPageButton="False" ButtonCssClass="datapager" />
<asp:NumericPagerField ButtonCount="10" NumericButtonCssClass="datapager" CurrentPageLabelCssClass="datapager" />
<asp:NextPreviousPagerField LastPageText=">>" NextPageText=">"
ShowLastPageButton="True" ShowPreviousPageButton="False" ButtonCssClass="datapager" />
</Fields>
</asp:DataPager>
</div>
<br />
<asp:ObjectDataSource ID="odsShiftDetails" runat="server"
SelectMethod="GetShiftInfoSortedPage" TypeName="EQ.DAL.ShiftInfoDB"
EnablePaging="True" SelectCountMethod="GetShiftInfoCount"
SortParameterName="sortExpression">
<SelectParameters>
<asp:ControlParameter ControlID="hfSearchCriteria" Name="searchCriteria" Direction="Input" />
</SelectParameters>
</asp:ObjectDataSource>
Code behind for Row Updation is:-
protected void gvShift_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftStartTime");
TextBox txtShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftEndTime");
TextBox txtWeekendShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftStartTime");
TextBox txtWeekendShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftEndTime");
Label lblUserecode = (Label)gvShift.Rows[e.RowIndex].FindControl("lblEditUserECode");
string userecode = lblUserecode.Text.ToString();
string _ShiftStart = txtShiftStartTime.Text.ToString();
string _ShiftEnd = txtShiftEndTime.Text.ToString();
string _WeekendShiftStart = txtWeekendShiftStartTime.Text.ToString();
string _WeekendShiftend = txtWeekendShiftEndTime.Text.ToString();
EmployeeQuotientCL.Entities.ConfigurationVariables _configVariables = new ConfigurationVariables();
string databaseConnectionString = _configVariables.ConnectionString;
SqlConnection sqlConnection = null;
if (((databaseConnectionString + string.Empty) != string.Empty))
{
DBConnect dbConnect = new DBConnect(_configVariables.ConnectionString);
sqlConnection = dbConnect.SQLConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
cmd.CommandText = "UPDATE UserInfo SET ShiftStartTime ='" + _ShiftStart + "',ShiftEndTime='" + _ShiftEnd.ToString() + "',Weekendshiftstarttime='" + _WeekendShiftStart.ToString() + "',Weekendshiftendtime='" + _WeekendShiftend.ToString() + "' WHERE UserECode=" + userecode.ToString();
sqlConnection.Open();
cmd.ExecuteNonQuery();
gvShift.DataSource = null;
gvShift.DataBind();
sqlConnection.Close();
}
}
catch (Exception ex)
{
}
}
While Updating the Rows in grid , I am getting the below error message.
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: >Updating is not supported by ObjectDataSource 'odsShiftDetails' unless the UpdateMethod is >specified.
Guide me how to fix this error. Thanks in advance.
You need to add an update method to your gridview. Look at this tutorial: Gridview ObjectdataSource
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]") %>' />