I've tried searching answers for how to save uploaded images using ajaxfileupload and save it to database and i found a couple of possible solutions. I integrated those codes and I have already tested the code in a small program and everything is working fine. But when i incorporate it in my actual project, it is not working and it is giving me an error that says "Object reference not set to an instance of an object". The new piece of code that i integrated is the ajax script, which will be fired in the OnClientUploadComplete, as well as the ajaxfileupload controls. Please see details below for more info.
Here is the aspx(i included everything in my code, but the main thing that you should look at is the two ajaxfileupload that has an ID of itemFileUpload1 and itemFileUpload2 and the ajax script above):
What I have tried:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="CreateBrands.aspx.cs" Inherits="Pages_CreateBrands" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="asp"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Music Store</title>
<script src="../Javascript/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
function uploadComplete(sender, args) {
var txt = document.getElementById("validatePicture");
hiddenfield id
txt.value = "1";
$.ajax({
type: "post",
url: "OpenPost.aspx/GetPath",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result1,result2) {
OnSuccess1(result1.d,result2.d);
},
error: function (xhr, status, error) {
OnFailure1(error);
}
});
}
function OnSuccess1(result1,result2) {
var pp1 = document.getElementById("PicturePath1");
pp1.value = result1;
var pp2 = document.getElementById("PicturePath2");
pp2.value = result2;
}
function OnFailure1(error) {
alert(error);
}
</script>
<link rel="stylesheet" href="~/Styles/jquery.bxslider.css"/>
<link rel="stylesheet" href="~/Styles/StyleSheet.css"/>
<link rel="stylesheet" href="~/Styles/font-awesome.min.css"/>
<link rel="shortcut icon" type="image/png" href="~/Images/rockSign.png"/>
<style type="text/css">
.auto-style1 {
width: 160px;
height: 37px;
}
.auto-style2 {
height: 37px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="wrapper">
<header id="main_header">
<div id="callout">
<h2>☎ 111222333</h2>
<p>Michigan State Kawasaki Iceland</p>
</div>
<h1>MUSIC STORE</h1>
</header>
<div class="clearfix"></div>
<nav id="nav_menu">
<ul id="nav">
<li><a href="~/Pages/Home.aspx" runat="server">HOME</a></li>
<li><a href="#">INSTRUMENTS</a>
<ul class="sub-menu">
<li><a href="~/Pages/GuitarBrands.aspx" runat="server">ELECTRIC GUITARS</a></li>
<li><a href="~/Pages/BassGuitarBrands.aspx" runat="server">BASS GUITARS</a></li>
<li><a href="#">DRUMS</a></li>
</ul>
</li>
<li><a href="#">AMPLIFIERS</a></li>
<li><a href="#">ACCESSORIES</a></li>
<li><a href="#">FEATURED ARTISTS</a></li>
<li><a href="#"><img src="../Images/cog.png" /></a>
<ul class="cog_submenu">
<li><a href="~/Pages/CreateBrands.aspx" runat="server">CREATE NEW BRAND</a></li>
<li><a href="#">USE EXISTING BRAND</a></li>
<li><a href="~/Pages/OverviewGuitarData.aspx" runat="server">GUITAR DATA OVERVIEW</a></li>
<li><a href="~/Pages/OverviewBassData.aspx" runat="server">BASS DATA OVERVIEW</a></li>
</ul>
</li>
</ul>
</nav>
<div id="content_area">
<h3> </h3>
<h3 class="headingTitle">Create New Brand(Step 1 of 2):</h3>
<table cellspacing="15" class="brandsTable">
<tr>
<td style="width: 160px; height: 37px;">
Brand Type:</td>
<td style="height: 37px">
<asp:CheckBox ID="brandTypeGuitar" runat="server" Text="Guitar" AutoPostBack="True" GroupName="brandType"/>
<asp:CheckBox ID="brandTypeBass" runat="server" Text="Bass" AutoPostBack="True" GroupName="brandType"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Brand Name:</td>
<td style="height: 37px">
<asp:TextBox ID="brandName" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
Brand Image:</td>
<td class="auto-style2">
<br/>
<asp:FileUpload ID="brandFileUpload" runat="server" />
<asp:Button ID="brandUploadImage" runat="server" Text="Upload Image" OnClick="brandUploadImage_Click" />
</td>
</tr>
</table>
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="btnSave" runat="server" CssClass="submitButton" Text="Save Brand" OnClick="btnSave_Click" />
<br/>
<br/>
<h3 class="headingTitle">Create New Item(Step 2 of 2):</h3>
<table cellspacing="15" class="brandsTable">
<tr>
<td style="width: 160px; height: 37px;">
Item Type:</td>
<td style="height: 37px">
<asp:RadioButton ID="itemType1" runat="server" Text="Guitar" AutoPostBack="False" GroupName="ItemType"/>
<asp:RadioButton ID="itemType2" runat="server" Text="Bass" AutoPostBack="False" GroupName="ItemType"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Brand:</td>
<td style="height: 37px">
<asp:TextBox ID="itemBrand" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Model:</td>
<td style="height: 37px">
<asp:TextBox ID="itemModel" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Price:</td>
<td style="height: 37px">
<asp:TextBox ID="itemPrice" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Image1:</td>
<td style="height: 37px">
<br />
<asp:AjaxFileUpload ID="itemFileUpload1" runat="server" OnUploadComplete="itemUploadImage1_Click" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Image2:</td>
<td style="height: 37px">
<br />
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server" OnUploadComplete="itemUploadImage2_Click" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1"/>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Description:</td>
<td style="height: 37px">
<asp:TextBox ID="itemDescription" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Neck Type:</td>
<td style="height: 37px">
<asp:TextBox ID="itemNeckType" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Body:</td>
<td style="height: 37px">
<asp:TextBox ID="itemBody" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Fretboard:</td>
<td style="height: 37px">
<asp:TextBox ID="itemFretboard" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Fret:</td>
<td style="height: 37px">
<asp:TextBox ID="itemFret" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Bridge:</td>
<td style="height: 37px">
<asp:TextBox ID="itemBridge" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Neck Pickup:</td>
<td style="height: 37px">
<asp:TextBox ID="itemNeckPickup" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Bridge Pickup:</td>
<td style="height: 37px">
<asp:TextBox ID="itemBridgePickup" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 160px; height: 37px;">
Item Hardware Color:</td>
<td style="height: 37px">
<asp:TextBox ID="itemHardwareColor" runat="server" BackColor="#FFFF66" BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px"></asp:TextBox>
</td>
</tr>
</table>
<asp:Label ID="lblResult2" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save Item" OnClick="Button1_Click"/>
</div>
<div class="clearfix"></div>
<footer>
<p>©All Rights Reserved</p>
</footer>
</div>
</form>
</body>
</html>
Here is the code-behind. I have also included everything in the aspx.cs file. The main thing that you should focus on is the method named itemUploadImage1_Click, itemUploadImage2_Click and Button1_Click. The error starts in the Button1_Click, which is pointing towards the string item_image1 and item_image2 stating that it is null;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
public partial class Pages_CreateBrands : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void ClearTextFields()
{
brandName.Text = "";
}
private void ClearTextFields2()
{
itemBrand.Text = "";
itemModel.Text = "";
itemPrice.Text = "";
itemDescription.Text = "";
itemNeckType.Text = "";
itemBody.Text = "";
itemFretboard.Text = "";
itemFret.Text = "";
itemNeckPickup.Text = "";
itemBridgePickup.Text = "";
itemBridge.Text = "";
itemHardwareColor.Text = "";
}
protected void brandUploadImage_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(brandFileUpload.FileName);
brandFileUpload.SaveAs(Server.MapPath("~/Images/Brands/") + filename);
lblResult2.Text = "Image " + filename + " successfully uploaded!";
}
catch (Exception)
{
lblResult.Text = "Upload failed!";
}
}
protected void itemUploadImage1_Click(object sender, AjaxFileUploadEventArgs e)
{
if (itemType1.Checked)
{
string filename = e.FileName;
Session["PicturePath1"] = filename;
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
else if (itemType2.Checked)
{
string filename = e.FileName;
Session["PicturePath1"] = filename;
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Bass/") + filename);
}
}
protected void itemUploadImage2_Click(object sender, AjaxFileUploadEventArgs e)
{
if (itemType1.Checked)
{
string filename = e.FileName;
Session["PicturePath2"] = filename;
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
else if (itemType2.Checked)
{
string filename = e.FileName;
Session["PicturePath2"] = filename;
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Bass/") + filename);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (brandTypeGuitar.Checked && !brandTypeBass.Checked)
{
try
{
string brand_image = ConnectionClassBrands.brandFileName;
string brand_name = brandName.Text;
ConnectionClassBrands.AddBrandsForOneType(brandTypeGuitar.Text, brand_name, brand_image);
lblResult.Text = "Upload successful!";
}
catch (Exception)
{
lblResult.Text = "Upload Failed!";
}
}
else if (brandTypeBass.Checked && !brandTypeGuitar.Checked)
{
try
{
string brand_image = ConnectionClassBrands.brandFileName;
string brand_name = brandName.Text;
ConnectionClassBrands.AddBrandsForOneType(brandTypeBass.Text, brand_name, brand_image);
lblResult.Text = "Upload successful!";
}
catch (Exception)
{
lblResult.Text = "Upload Failed!";
}
}
else if (brandTypeGuitar.Checked && brandTypeBass.Checked)
{
try
{
string brand_image = ConnectionClassBrands.brandFileName;
string brand_name = brandName.Text;
ConnectionClassBrands.AddBrandsForTwoTypes(brandTypeGuitar.Text, brandTypeBass.Text, brand_name, brand_image);
lblResult.Text = "Upload successful!";
}
catch (Exception)
{
lblResult.Text = "Upload Failed!";
}
}
else
{
lblResult.Text = "Upload Failed!";
}
ClearTextFields();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (itemType1.Checked)
{
int item_type = ConnectionClassBrands.GetIdByType(itemType1.Text);
int item_brandId = ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
string item_model = itemModel.Text;
double item_price = Convert.ToDouble(itemPrice.Text);
string item_image1 = Session["PicturePath1"].ToString();
string item_image2 = Session["PicturePath2"].ToString();
string item_description = itemDescription.Text;
string item_necktype = itemNeckType.Text;
string item_body = itemBody.Text;
string item_fretboard = itemFretboard.Text;
string item_fret = itemFret.Text;
string item_bridge = itemBridge.Text;
string item_neckpickup = itemNeckPickup.Text;
string item_bridgepickup = itemBridgePickup.Text;
string item_hardwarecolor = itemHardwareColor.Text;
ConnectionClassGuitarItems.AddStringInstrumentItems(item_type,item_brandId,item_model,item_price,item_image1,item_image2,
item_description,item_necktype,item_body,item_fretboard,item_fret,item_bridge,item_neckpickup,
item_bridgepickup,item_hardwarecolor);
lblResult2.Text = "Upload successful!" + item_image1 + " and " + item_image2;
}
else if (itemType2.Checked)
{
try
{
int item_type = ConnectionClassBrands.GetIdByType(itemType2.Text);
int item_brandId = ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
string item_model = itemModel.Text;
double item_price = Convert.ToDouble(itemPrice.Text);
string item_image1 = Session["PicturePath1"].ToString();
string item_image2 = Session["PicturePath2"].ToString();
string item_description = itemDescription.Text;
string item_necktype = itemNeckType.Text;
string item_body = itemBody.Text;
string item_fretboard = itemFretboard.Text;
string item_fret = itemFret.Text;
string item_bridge = itemBridge.Text;
string item_neckpickup = itemNeckPickup.Text;
string item_bridgepickup = itemBridgePickup.Text;
string item_hardwarecolor = itemHardwareColor.Text;
ConnectionClassGuitarItems.AddStringInstrumentItems(item_type, item_brandId, item_model, item_price, item_image1, item_image2,
item_description, item_necktype, item_body, item_fretboard, item_fret, item_bridge, item_neckpickup,
item_bridgepickup, item_hardwarecolor);
lblResult2.Text = "Upload successful!";
ClearTextFields2();
}
catch (Exception ex)
{
lblResult2.Text = ex.Message;
}
}
}
}
I'm really confused as to why it is null. I have really tried this piece of code in a small program and everything is working fine. I hope you can help me on this one.
Here is also the stack trace of the error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.
Source Error:
Line 159: string item_model = itemModel.Text;
Line 160: double item_price =
Convert.ToDouble(itemPrice.Text);
Line 161: string item_image1 =
Session["PicturePath1"].ToString();
Line 162: string item_image2 =
Session["PicturePath2"].ToString();
Line 163: string item_description = itemDescription.Text;
Source File: c:\Users\User1\Documents\Visual Studio
2015\WebSites\MusicStore\Pages\CreateBrands.aspx.cs Line: 161
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an
object.]
Pages_CreateBrands.Button1_Click(Object sender, EventArgs e) in
c:\Users\User1\Documents\Visual Studio
2015\WebSites\MusicStore\Pages\CreateBrands.aspx.cs:161
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
+204
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.
RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint) +1639