I trying to save employee image in employee database. I have three field in database table empid, empname, empimage. Here is my database part.
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)
In the button click event, i have written the following code:
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(#enm, #eimg)SELECT ##IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}
And Here is my form:
<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
 
<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
<br />
<hr />
<asp:Image ID="Image1" style="width:200px" Runat="server" />
But when I am uploading any image and clicking on submit button getting this error "Object reference not set to an instance of an object." Pls somebody point out my error.
Thanks,
Sumit
Object Reference errors only occur when an object is not initialized and you try to reference it. This could be any object you are referencing within your code. If you step through the code while debugging, you can see exactly which reference is null.
You have an if statement that initializes the imgByte object:
imgByte = new Byte[File.ContentLength];
If the img object turns out to be null, that code does not run. Then you reference the imgByte here, regardless of whether or not the img was null:
cmd.Parameters.AddWithValue("#eimg", imgByte);
Check the the HttpPostedFile object itself is not null and move your imgByte object initialization outside the if statement. Also, the name File is already used by the System.IO.File object. You may want to rename it just to be safe.
I would rearrange your ADO.NET code a bit - make it safe and more reliable; also, I would make sure to separate the two SQL statements in your "sql" string by a semicolon to make it clear to SQL that this is two commands, really:
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
using(connection = new SqlConnection(conn))
{
string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " +
"VALUES(#enm, #eimg); SELECT ##IDENTITY";
using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
{
cmd.Parameters.AddWithValue("#enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("#eimg", imgByte);
connection.Open();
int id = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
lblResult.Text = String.Format("Employee ID is {0}", id);
}
}
Any luck with this?? Otherwise you should really step through the code in the debugger and see where in your code you reference something that is NULL (and you don't check for that condition).
Marc
While i am debugging this code i am
getting exception in this
line..."string conn =
ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"
Exception is: Object reference not set
to an instance of an object.
You need to add a connection string named EmployeeConnString to web.config.
Your exception handler does not distinguish where exactly an exception occurred, and issues a single error message for any possible error.
Related
when i Bind the dropdownlistHostelRoomType, it binds with empty spaces left above.. i dont have any idea why this is happening. help me getting out from this issue please.. My Code:
<div>
<fieldset>
<legend>Hostel Details </legend>
<asp:Label ID="LabelHostelRoomType" runat="server" Text="Room Type"></asp:Label>
<asp:DropDownList ID="DropDownListHostelRoom" runat="server" DataTextField="HTypeName"
DataValueField="_HRTypID" OnSelectedIndexChanged="DropDownListHostelRoom_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridViewHostelRoom" runat="server">
</asp:GridView>
</fieldset>
</div>
private void FillHostelRoomType()
{
SqlConnection cn = new SqlConnection(#"Data Source=.;Initial Catalog=_uniManagement;Integrated Security=True");
string sqlDropdownHostelRoom = String.Format("SELECT [_HRTypID], [HTYPeNAME] FROM [_HOSTELS_Room_TYPE]");
SqlCommand cmd = new SqlCommand(sqlDropdownHostelRoom);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownListHostelRoom.DataSource = dt;
DropDownListHostelRoom.DataBind();
}
protected override void OnInit(EventArgs e)
{
DropDownListHostelRoom.AppendDataBoundItems = true;
DropDownListMemberType.AppendDataBoundItems = true;
FillHostelRoomType();
FillHostelMember();
base.OnInit(e);
}
Most likely, there are empty spaces in the source database. In your SQL statement, you should be able to use RTRIM() around the field names to eliminate the issue.
Another possible cause might be that the field in the DB is CHAR with a specified length. If that is the case, even if there are no spaces, retrieving it will always give you exactly that many spaces, so SQL Server will pad the end with enough blank spaces to fit.
For example, a field defined as CHAR(10) with the data "DAVID" in it will be returned as "DAVID " (David appended with five blank spaces to bring the total up to 10)
Either way, RTRIM should fix it.
string sqlDropdownHostelRoom = String.Format("SELECT [_HRTypID], RTRIM([HTYPeNAME]) AS HTYPeNAME FROM [_HOSTELS_Room_TYPE]");
I've stumbled upon an issue and can't figure it out on my own. Hope someone could help me resolve it.
So, I have a simple stored procedure in a SQL Server 2005 database
CREATE PROCEDURE spTest
#pin varchar(128)
AS
BEGIN
SELECT #Pin as Param
END
and an asp.net page with a SqlDataSource and a GridView control in an application (VS2008)
<asp:SqlDataSource
ID="sds2"
runat="server"
ConnectionString="..."
SelectCommand="spTest"
SelectCommandType="StoredProcedure"
>
<SelectParameters>
<asp:QueryStringParameter Name="pin" QueryStringField="pin" DbType="String"/>
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="gv" runat="server" DataSourceID="sds2"></asp:GridView>
As you can see, the code is straightforward. Nevertheless, if I don't bother specify the pin on the url (.../Default.aspx instead of .../Default.aspx?pin=somevalue) or specify an empty line (.../Default.aspx?pin=) there is no any call to the stored procedure (I check it with SQL Server Profiler).
Moreover, if I replace the QueryStringParameter with a simple
<asp:Parameter Name="pin" DbType="String" />
and do not point out DefaultValue value, the situation repeats and no calls to the stored procedure are made. What is the reason of such a behaviour?
I'm quite a new to the asp.net and possibly overlook something, but I even tried to do the same in code-behind file programmatically instead of declaratively and the result is the same. The only thing I could find out is that in such case a Selecting event of the SqlDataSource is fired, but the Selected is not. Maybe some kind of an error happens?
Anyway, any kind of help would be greatly appreciated.
The SqlDataSource object has a property called CancelSelectOnNullParameter. Its default value is true, so I think the behavior you're seeing is expected, albeit not obvious. Try setting this property to false.
<asp:SqlDataSource
ID="sds2"
runat="server"
ConnectionString="..."
SelectCommand="spTest"
SelectCommandType="StoredProcedure"
CancelSelectOnNullParameter="false"
>
Additionally, you may find the ConvertEmptyStringToNull property of the Parameter class (QueryStringParameter extends this) to be of some use, depending on if/how your stored proc handles null values. Its default value is true as well.
Try this out.
Create a method which will return db null if parameter is not passed in the stored procedure
public static object GetDataValue(object o)
{
if (o == null || String.Empty.Equals(o))
return DBNull.Value;
else
return o;
}
Create a method which will called the stored procedure and fill the dataset.
public DataSet GetspTest(string pin)
{
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[1];
oParam[0] = new SqlParameter("#Pin", GetDataValue(pin));
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "spTest", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
Now bind the dataset to gridview
private void GvTest()
{
DataSet oDsGvspTest = new DataSet();
string pin = Request.QueryString["Pin"];
oDsGvspTest = GetspTest(pin);
if (oDsGvspTest.Tables[0].Rows.Count > 0)
{
Gv.DataSource = oDsGvspTest;
Gv.DataBind();
}
}
Now called this method on page_load event
if(!IsPostBack)
{
GvTest();
}
If found it useful,please mark it as your answer else let me know...
I am coding "List all Product" page in asp.net. I did the connection from the DB to ViewList. Now I have to make the products clickable. What I have coded so far in the asp part is , as it follows:
<div class="image">
<asp:HyperLink ID="HyperLinkSaleDesign" runat="server" NavigateUrl='<%# Eval("ID" , "~/EN/ViewTemplate.aspx?id={0}") %>'>
<asp:Image ID="ImageSaleDesign" runat="server" Width="247" Height="150" ImageUrl='<%# Eval("thumb") %>' />
</asp:HyperLink>
</div>
The navigation URL works and I can see the selected "?id={0}".
However I cannot pass the data correctly , so the SQL query on the next page does not work.
I am not sure how to pass this value to the Select statement. Here is what I have done so far:
String IDquery = ("QueryStringParameter[ID]"); // doesn't work
try
{
string ConnectionString = WebConfigurationManager.ConnectionStrings["Twebconfig"].ConnectionString;
SqlConnection viewTemplate = new SqlConnection(ConnectionString);
SqlDataAdapter viewTemplateSet = new SqlDataAdapter("SELECT " +
" * FROM saleDesigns WHERE ID = #IDquery", viewTemplate); // doesn't seem to see the variable
Data Binding - etc. etc. etc
}
catch (Exception err)
{
mylabel.Text = "Invalid " + err.Message;
}
I am open to any suggestions.
Thank you.
I'm a bit confused by your code, but it looks like you just need to retrieve the id from QueryString and build a SQL query with it, right?
Is this what you're trying to do?:
int id = int.Parse(Request.QueryString["id"]);
You can put the query together using the ID from QueryString, you can do something like this:
//just an example - should be parameterized to avoid injection
string query = String.Format("SELECT ID, Col1, Col2 FROM Table1 WHERE ID={0}", Request.QueryString["ID"]);
This is the way it works for me:
int v = 0;
try
{
int v = int.Parse(Request.QueryString["id"]);
}
catch (Exception e)
{}
if (v > 0)
{
try
{
string ConnectionString = WebConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);//explisionremoteEntities
string query = String.Format("SELECT * FROM table WHERE ID={0}", Request.QueryString["ID"]);
SqlDataAdapter viewTemplateSet = new SqlDataAdapter(query, conn);
}
catch
{
//code in here
}
}
I wrote the code to query the database, but now do not know how to get the text into my two labels 'txtTitle' & 'txtBody'
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["blcDocumentationConnectionString"].ConnectionString);
// Create Command Object
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
pnlNew.Visible = false;
pnlView.Visible = true;
try
{
// Open Connection
thisConnection.Open();
// Create SELECT statement with named parms
nonqueryCommand.CommandText = "SELECT DocumentTitle,DocumentBody FROM tblDocument WHERE DocumentID = #DocumentID";
// Add parms to Command parms collection
nonqueryCommand.Parameters.AddWithValue("#DocumentID", GridView1.SelectedValue);
// Execute query statement
nonqueryCommand.ExecuteNonQuery();
// Populate Labels
GridViewRow row = GridView1.SelectedRow;
lblTitle.Text = row.Cells[1].Text;
lblBody.Text = row.Cells[2].Text;
}
finally
{
// Close Connection
thisConnection.Close();
}
}
<asp:Panel ID="pnlView" runat="server" Visible="False" CssClass="pnlView">
<h1 style="background-color: #CCE6FF">
<asp:Label ID="lblTitle" runat="server" Text="Label"></asp:Label></h1>
<p>
<asp:Label ID="lblBody" runat="server" Text="Label"></asp:Label></p>
<p style="background-color: #EFEFEF">
<asp:Button ID="btnEdit" runat="server" Text="Edit This Document" OnClick="btnEdit_Click" /> or
cancel</p>
</asp:Panel>
Your code shows that you have a table filled with documents IDs (I'm assuming you already bound this correctly in some other part of your code)
You used the SelectedIndexChanged event correctly, but why are you executing another query inside? If executing the query is intentional, why are you binding your labels to old data? row.cells[].value holds old information, not the information you re-queried. If you want the information you re-queried for, get that info directly from the result set. Also, that result set will return nothing unless you change nonqueryCommand.ExecuteNonQuery(); to nonqueryCommand.ExecuteDataSet();
Reiterating what User:rkw mentioned above. ExecuteNonQuery will not get any data back from the database. You need to use either DataReader ( http://msdn.microsoft.com/en-us/library/haa3afyz.aspx ) or use the ExecuteDataset and put the information into a DataSet and then read from it. When you say ExecuteNonQuery you are basically telling the SQL server to execute commands but not expecting any data back from the SQL Server.
It's pretty difficult to show code for ASP.NET here, so I will try my best to describe my problem.
I have a FileUploadControl and a Button that calls a function when it's clicked. It seems that the Button function works when there is nothing chosen for my FileUploadControl. However, when there is something chosen in the FileUploadControl (I have selected a file to upload), there is a problem when I click the button. It completely does not matter what the function does (it could just be writing to a label, even when it has nothing to do with the FileUploadControl). The error I get is:
This webpage is not available.
The webpage at http://localhost:2134/UploadMedia/Default.aspx might be temporarily down or it may have moved permanently to a new web address.
I have searched on Google, and people seem to have had problems with this, but different causes from me. They have said that their ASP.NET Development Server port is actually different from their port in the address bar. This is not the case for me.
Also, another problem people have had is with Use Dynamic Ports. I have tried both true and false. I have also tried different ports, and I have always gotten the same error.
This is really driving me crazy because it doesn't matter what the code in the buttonFunction is, it doesn't work as long as there is something in the FileUploadControl. If there is nothing, it seems to work fine.
Here is the code for the ASP.NET Controls:
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" OnClick="uploadClicked" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
And this is the code for the button function:
protected void uploadClicked(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//Check if the entered username already exists in the database.
String sqlDupStmt = "Select songPath from Songs where songPath ='" + Server.MapPath("~/Uploads/") + filename + "'";
SqlConnection sqlDupConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True;");
SqlCommand sqlDupCmd = new SqlCommand(sqlDupStmt, sqlDupConn);
sqlDupCmd.Connection.Open();
SqlDataReader sqlDupReader = sqlDupCmd.ExecuteReader(CommandBehavior.CloseConnection);
if (sqlDupReader.Read())
{
StatusLabel.Text = "Upload status: The file already exists.";
sqlDupReader.Close();
}
else
{
sqlDupReader.Close();
//See "How To Use DPAPI (Machine Store) from ASP.NET" for information about securely storing connection strings.
String sqlStmt = "Insert into Songs values (#songpath);";
SqlConnection sqlConn = new SqlConnection(#"Data Source = .\SQLEXPRESS; AttachDbFilename = |DataDirectory|\Database.mdf; Integrated Security = True; User Instance = True; uid=sa; pwd=password;");
SqlCommand cmd = new SqlCommand(sqlStmt, sqlConn);
SqlParameter sqlParam = null;
//Usage of Sql parameters also helps avoid SQL Injection attacks.
sqlParam = cmd.Parameters.Add("#userName", SqlDbType.VarChar, 150);
sqlParam.Value = Server.MapPath("~/Uploads/") + filename;
//Attempt to add the song to the database.
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename);
songList.Items.Add(filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
finally
{
sqlConn.Close();
}
}
}
}
But this buttonfunction provides the same results:
protected void uploadClicked(object sender, EventArgs e)
{
StatusLabel.Text = "FooBar";
}
Has anyone had this problem before, or might know what the cause is?
Thanks!
My friend helped me figure it out. It was because ASP.NET only allowed uploads of 4MB sizes. I had to go into the web.config or the machine.config file and change the value of MaxRequestLength to be larger than 4096. This solved it.