FileUpload1 does not exist in current context - c#

I'm trying to create a site that allows the user to upload a song and download any song that was uploaded. I'm using MySQL to store any uploaded song. I think I have the HTML and C# code right but it keeps throwing me an error saying FileUpload1 does not exist in the current context, you can use a navigation bar to switch context. My C# code is as follows.
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.IO;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Configuration;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = "server=localhost;user id=root;database=music;persistsecurityinfo=True";
using (MySqlConnection con = new MySqlConnection(strConnString))
{
using (MySqlCommand command = new MySqlCommand())
{
con.Open();
string SQL = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
command.CommandText = SQL;
command.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
command.Parameters.AddWithValue("#ContentType", "audio/mpeg3");
command.Parameters.AddWithValue("#Data", bytes);
command.Connection = con;
command.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
Here is my HTML for the site:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Music.aspx.cs" Inherits="Default3" %>
<asp:Content ID="music" runat="server" ContentPlaceHolderID ="ContentPlaceHolder1">
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click"/>
<hr/>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle-BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="FileName"/>
        <asp:TemplateField>
            <ItemTemplate>
                <object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
                    width="240" height="20" id="dewplayer">
                    <param name="wmode" value="transparent"/>
                    <param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
                </object>
            </ItemTemplate>
       </asp:TemplateField>
        <asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download"/>
   </Columns>
</asp:GridView>
</asp:Content>

Your code behind defines a partial class "Default3". I assume your aspx page is named "Default3", and visual studio has generated the code to instantiate the elements in that aspx page. That generated code is also a partial class "Default3", but you will notice in that generated code, that the partial class is defined under a namespace. Your code behind does not define the rest of that class under any namespace, so it does not have access to the same objects. Looks like at some point you deleted the namespace specification out of your code behind.

Related

MicrosoftAjax.js - POST 500 (Internal Server Error) upon PostBack

I'm working on an ASP.NET web application. Where I have added an ascx controller with an asp:updatepanel inside. The problem is now that when try to make an update it gives the following error:
MicrosoftAjax.js:5 POST http://localhost:49735/ 500 (Internal Server Error)
executeRequest # MicrosoftAjax.js:5
executeRequest # MicrosoftAjax.js:5
invoke # MicrosoftAjax.js:5
_onFormSubmit # MicrosoftAjaxWebForms.js:5
(anonymous function) # MicrosoftAjax.js:5
b # MicrosoftAjax.js:5
my ascx file looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SearchResults.ascx.cs" Inherits="CarParts24.Controls.Search.Results.SearchResults" %>
<asp:UpdatePanel ID="UpdPnlSearchResults" runat="server">
<ContentTemplate>
<span id="search-result-json" class="hidden">
<asp:HiddenField ID="hiddenSearchResults" runat="server" />
</span>
<%--<asp:Panel ID="PanelResult" runat="server">--%>
<%-- Some ordinary HTML code --%>
<%--</asp:Panel>--%>
</ContentTemplate>
</asp:UpdatePanel>
and the codebehind:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CarParts24.Controls.Search.Results
{
public partial class SearchResults : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PanelResult.Visible = false;
}
public void ShowResults(DataTable datatable)
{
hiddenSearchResults.Value = JsonConvert.SerializeObject(datatable);
PanelResult.Visible = true;
}
}
}
I found the problem, it was due to the <asp:HiddenField ID="hiddenSearchResults" runat="server" /> doing a postback when updating. changing it to a <asp:Literal ID="hiddenSearchResults" runat="server" /> fixed the problem

Fatal error encountered during program execution in c# asp.net

Here i am trying to insert values from form to database.when i fill in the form and hit submit, i am getting a error window saying fatal error encountered during program execution.
here is my code.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
public partial class dashboard : System.Web.UI.Page
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submit_Click(object sender, EventArgs e)
{
var b = RadioButtonList1.SelectedItem.ToString();
try
{
conn.Open();
MySqlCommand cmdo = new MySqlCommand("Insert into application (applicant_fullname,applicant_age,applicant_dob,applicant_gender,applicant_residential_address) values (#Name,#password,#Email)", conn);
cmdo.Parameters.Clear();
cmdo.Parameters.AddWithValue("#fullname", fullname.Text);
cmdo.Parameters.AddWithValue("#age", age.Text);
cmdo.Parameters.AddWithValue("#dob", dateofbirth.Text);
cmdo.Parameters.AddWithValue("#gender",b);
cmdo.Parameters.AddWithValue("#resident", resident.Text);
cmdo.ExecuteNonQuery();
cmdo.Parameters.Clear();
cmdo.Dispose();
ShowMessage("Registered successfully......!");
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
finally
{
conn.Close();
}
}
void ShowMessage(string msg)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + msg + "');</script>");
}
}
asp code:
<form id="form1" runat="server">
<table class="applytable">
<tr><td>Full name</td><td><asp:TextBox ID="fullname" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Age</td><td><asp:TextBox ID="age" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Date Of Birth</td><td><asp:TextBox ID="dateofbirth" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Gender</td><td><asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Value="Male"></asp:ListItem>
<asp:ListItem Value="Female"></asp:ListItem>
</asp:RadioButtonList></td></tr>
<tr><td>Residential Address</td><td><asp:TextBox id="resident" TextMode="multiline" Columns="50" Rows="5"
runat="server" Height="58px" Width="194px" /></td></tr>
<tr><td>Permanant Address</td><td><asp:TextBox id="permenant" TextMode="multiline" Columns="50" Rows="5"
runat="server" Height="68px" Width="192px" /></td></tr>
<tr><td>Parent/Guardian name</td><td><asp:TextBox ID="parentname" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>E-mail Address</td><td><asp:TextBox ID="emailid" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Phone Number</td><td><asp:TextBox ID="phoneno" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td></td><td><asp:Button ID="submitpage1" runat="server"
onclick="submit_Click" Text="Submit" /></td></tr>
</form>
How can i solve this? what am i doing wrong here?
I can clearly see your insert query is wrong.Your column and values does not match.
So I would recommend to run that query in mysql editor first to check insert query works.
Moreover you are adding values in parameter which are not mentioned in your queries.

dropdownlist error in c# code

i want to show a value in DropDownList at page load and the value is "1 Year".
here is my Database Table
id instal
0 Choose
6 6 Month
12 1 Year
24 2 Year
36 3 Year
here is my ASPX code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="instal" DataValueField="id"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:paconn %>"
SelectCommand="SELECT * FROM [cms_instal] ORDER BY [id]">
</asp:SqlDataSource>
</asp:Content>
and its my C# code:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;
using System.Web.SessionState;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.Text = "1 Year";
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
but problem is that when my page is loaded it gives an error
"'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value"
i am using ASP.Net C#, SQL Server 2008.
The text property of a DropDownList gets or sets the SelectedValue. Since your DataValueField is set to "id", you would need to set the Text property to "12".
Move the text to the LoadComplete event
void Page_LoadComplete(object sender, EventArgs e)
{
DropDownList1.Text = "1 Year";
}
The list binding has not occurred in page load so the list is not able to take another value which is not in the list. Setting the value after page load will allow it to use an existing value.

Session data from textbox inputed by user

I have this project where I want to transfer data from textbox1 with session "sam" on the about.aspx on its label. The problem is that when I input a number, it is not shown on label. My problem is that I type something on the "Αριθμός Επιβατών:" textbox (a number for example) and after that I click submit I need to get the number on the about page next to "Ari8mos epivatwn :"
Defaultaspxcs.txt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click2(object sender, EventArgs e)
{
string txt = TextBox1.Text;
Session["sam"] = txt;
}
}
}
Aboutaspxcs.txt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Session["sam"];
}
}
}
Aboutaspx.txt:
<%# Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="About.aspx.cs" Inherits="WebApplication4.About" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
Ari8mos epivatwn :
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</p>
</asp:Content>
https://www.dropbox.com/sh/4ftlddfhqo8n99p/gm-TNvol0S
It's likely that the content for the Label is being written twice, and not in the order your expect.
Start by familiarizing yourself with the asp.net page life-cycle
You will notice that PageLoad is called long before Render.
So, the page loads like this:
PageLoad Label text set to some number from your code
A bunch of other stuff
Render sets the Label text to "Label" instead, since that is what you have defined in your chtml.
Review this part of your code:
...
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
...
Try this instead:
...
<asp:Label ID="Label1" runat="server"></asp:Label>
...

Displaying Database Images in Gridview with HttpHandler

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

Categories

Resources