Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
i am trying this code to insert a data into a table but i have an error
Object reference not set to an instance of an object.
on
string id = cmd.Parameters["id"].Value.ToString();

my complete code is given below with sql code..

What I have tried:

table in sql.
create table addpinrequest(Appmstregno varchar(100), Qty varchar(100),Amount int, paymode varchar(100), [transaction] varchar(200), bankname varchar(200), branchname varchar(200), accountno varchar(200), ifsc varchar(100), [filename] varchar(200), msg varchar(200), id varchar(100)); 


stored procedure.
go 
alter procedure spaddpinrequest(@Appmstregno varchar(100), @Qty varchar(100), @Amount int, @paymode varchar(100), @transaction varchar(200), @Bankname varchar(200),@Branchname varchar(200),@Accountno varchar(200),@Ifsc varchar(100), @FileName varchar(200), @msg varchar(200),@id varchar(100))
as
begin
insert into addpinrequest(Appmstregno,Qty,Amount,paymode,[transaction], bankname,branchname,accountno,ifsc,[filename],msg,id) values(@Appmstregno,@Qty,@Amount,@paymode,@transaction,@Bankname,@Branchname,@Accountno,@Ifsc,@FileName,@msg,@id);
end


sp page code in appcode.
public static string AddPinRequest = "spaddpinrequest";


main page code.
protected void Button1_Click(object sender, EventArgs e)
   {
       if (datacheck())
       {
           int totalpackamount = Convert.ToInt32(((Label)gvPins.FooterRow.FindControl("lblTotalAmount")).Text);

           if (totalpackamount == Int32.Parse(txtAmount.Text))
           {
               string fileName = string.Empty;

               if (uploadFile.HasFile)
               {
                   fileName = "PAN/" + uploadFile.FileName;
                   uploadFile.SaveAs(Server.MapPath(fileName));
               }

               Int32 count = 0;
               DbCommand cmd = DataAccess.CreateCommand();
               cmd.CommandText = SP.AddPinRequest;

               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Appmstregno", DbType.String, _master.UserMemberId));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Qty", DbType.String, ((Label)gvPins.FooterRow.FindControl("Label1")).Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Amount", DbType.Int32, txtAmount.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@paymode", DbType.String, ddlPaymentMode.SelectedItem.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@transaction", DbType.String, txtTransaction.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Bankname", DbType.String, txtBankName.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@@Accountno", DbType.String, txtAccountNo.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Ifsc", DbType.String, txtIFSC.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@FileName", DbType.String, fileName));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@msg", DbType.String, txtComment.Text));
               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Id", DbType.String, DBNull.Value, ParameterDirection.Output));

               int i = DataAccess.ExecuteNonQuery(cmd);
               string id = cmd.Parameters["@Id"].Value.ToString();

               if (i > 0)
               {
                   foreach (GridViewRow gr in gvPins.Rows)
                   {
                       if (gr.RowType == DataControlRowType.DataRow)
                       {
                           if (((CheckBox)gr.FindControl("chkSelectPin")).Checked)
                           {
                               cmd = DataAccess.CreateCommandText();
                               cmd.CommandText = "insert into PinDetail (RequestId, Qty, PlanName, TotalAmount, PlanId, Appmstregno) values (@RequestId, @Qty, @PinValue, @PinValue, @PlanId, @Appmstregno)";
                               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "PinValue", DbType.String, gr.Cells[2].Text));
                               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "PlanId", DbType.String, gr.Cells[1].Text));
                               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "Qty", DbType.String, ((TextBox)gr.FindControl("txtNoOfPins")).Text));
                               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "Appmstregno", DbType.String, _master.UserMemberId));
                               cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "RequestId", DbType.String, id));

                               count += DataAccess.ExecuteNonQuery(cmd);
                               cmd.Parameters.Clear();
                           }
                       }
                   }
               }

               if (count > 0)
               {
                   reset();
                   Message.Show("Thanks, Request Send successfully. We will contact you soon..");
               }
               else
               {
                   Message.Show("Sorry!! There is something wrong please contact Administrator.");
               }
           }
           else
           {
               Message.Show("Sorry!!! Amount is less Then or Not equal to Total pin cost");
           }
       }
   }
C#
<pre lang="c#">
Posted
Updated 26-Apr-20 2:54am

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
The simple answer is going to be set a value to it; because as it is written there is never a value assigned to it.
C#
cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "@Id", DbType.String, DBNull.Value, ParameterDirection.Output));
So you have created an OUTPUT parameter within C# and have populated it with NULL. This is fine so far.
Now let's look at the SP you have created, which has a few comments added
SQL
alter procedure spaddpinrequest(
   @Appmstregno varchar(100), 
   @Qty         varchar(100), 
   @Amount      int, 
   @paymode     varchar(100), 
   @transaction varchar(200), 
   @Bankname    varchar(200),
   @Branchname  varchar(200),
   @Accountno   varchar(200),
   @Ifsc        varchar(100), 
   @FileName    varchar(200), 
   @msg         varchar(200),
   @id          varchar(100)  -- NOTE: Not identified as OUTPUT, no default value
) as
begin
   insert into addpinrequest(
	Appmstregno,  Qty,        Amount,  paymode,     [transaction], bankname
     ,  branchname,   accountno,  ifsc,    [filename],  msg,           id
   ) values(
	@Appmstregno, @Qty,       @Amount, @paymode,     @transaction, @Bankname
      , @Branchname,  @Accountno, @Ifsc,   @FileName,    @msg,         @id
   );
end
So what we have here is a Stored Procedure which has not OUTPUT parameters identified, so they are not going to be returned. Furthermore, the value for @id is never set.

Now for what I would be doing....
Within the C# portion, I would have defined the parameter as a local variable with a default value that I could capture later.
C#
var spOut = DataAccess.CreateParameter(cmd, "@Id", DbType.String, "InitValue", ParameterDirection.Output)
cmd.Parameters.Add(spOut);

int i = DataAccess.ExecuteNonQuery(cmd);
string id = spOut.Value.ToString();

if (id == "InitValue") { throw new Exception("SP did not change the value"); }
Within the Stored Procedure, you need to add the OUTPUT identifier within the declaration portion. I also set a default value just in case the calling code does not pass a value you... This can also captured later by the calling code
SQL
ALTER PROCEDURE spaddpinrequest(
  -- 
   @id          varchar(100)  = "No Value Passed In" OUTPUT
) AS
C#
if (id == "InitValue") { throw new Exception("SP did not change the value"); }
if (id == "No Value Passed In") { throw new Exception("No Value Passed In"); }
Something else that I do is check that rows affected variable (i) a little more thoroughly; we know that it should return 1 which you are checking for, but what are you going to do if it returns a 2? Or 100?
C#
int i = DataAccess.ExecuteNonQuery(cmd);
string id = spOut.Value.ToString();

if (i != 1) { throw new Exception("Unexpected results from INSERT Query"); }
else {
   foreach (GridViewRow gr in gvPins.Rows)
So right now your code should work... but the procedure never sets a value to it, and there is nothing in your code that even hints at what should be going into it. Just know that somewhere within the body of the procedure you may need to add a line like this to return a value
SQL
SET @id = -- this is going to be up to you
This is only for the first block of code. I did notice that you do reuse the cmd object further down, and then you start adding parameters to it. You should be aware that the parameter collection may still has values in it from the first query, which can be cleared out with cmd.Parameters.Clear();.
 
Share this answer
 
v2
Comments
Member 14743579 26-Apr-20 12:08pm    
create table addpinrequest(Appmstregno varchar(100), Qty varchar(100),Amount int, paymode varchar(100), [transaction] varchar(200), bankname varchar(200), branchname varchar(200), accountno varchar(200), ifsc varchar(100), [filename] varchar(200), msg varchar(200), id int identity(1,1) primary key);

go
alter procedure spaddpinrequest(@Appmstregno varchar(100), @Qty varchar(100), @Amount int, @paymode varchar(100), @transaction varchar(200), @Bankname varchar(200),@Branchname varchar(200),@Accountno varchar(200),@Ifsc varchar(100), @FileName varchar(200), @msg varchar(200),@id int output)
as
begin
insert into addpinrequest(Appmstregno,Qty,Amount,paymode,[transaction], bankname,branchname,accountno,ifsc,[filename],msg) values(@Appmstregno,@Qty,@Amount,@paymode,@transaction,@Bankname,@Branchname,@Accountno,@Ifsc,@FileName,@msg);
set @id=scope_identity();
end
this is my sql codes can i do this
MadMyche 26-Apr-20 12:51pm    
Yes.
You are going to need to change the C# code as that parameter will now be an INT instead of a string.
Changes I would do:
1. Rename the ID to something a little more intuitive; such as AddPinRequestID
2. Move that IDentity field to be the first column in the table
3. Rename the Transaction and Filename fields, they are "reserved" words"
4. Pass in a 0 from C# to the ID field
5. Set the @ID field to have a default value of -1 in the declaration state
6. Set the @ID filed to -2 BEFORE the INSERT occurs
7. Keep the SET @ID at the end

value to -2 before the

I generally would put the ID at the beginning of the table DDL; and I probably would change the name to be a little more specific, something like AddPinRequestID.
Member 14743579 26-Apr-20 14:19pm    
cmd.Parameters.Add(DataAccess.CreateParameter(cmd, "Qty", DbType.String, ((Label)gvPins.FooterRow.FindControl("Label1")).Text));
this code is correct to store the value from labe1(gridview footer) into the table.
MadMyche 26-Apr-20 14:51pm    
It looks that you have it as a string in C# and a varchar in SQL, so it should be OK
Member 14743579 26-Apr-20 15:11pm    
my above code is not working after change same error arise
object reference problem in this line
string id = (cmd.Parameters["@Id"].Value.ToString());

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900