Procedure or function has too many arguments specified - c#

Below is my stored procedure for insert:
CREATE PROCEDURE [dbo].[Insertaddress_Master]
(
#add_Zip nvarchar(20),
#add_FullAddress nvarchar(250),
#add_user_Id int,
#add_CreatedDate datetime,
#add_UpdatedDate datetime,
#add_DeletedDate datetime,
#add_IsDeleted bit,
#add_IsPrimary bit,
#add_cntm_Id int,
#add_alt_No nvarchar(20)
)
As
BEGIN
SET NOCOUNT ON
Insert Into [address_Master]
(
[add_Zip],
[add_FullAddress],
[add_user_Id],
[add_CreatedDate],
[add_UpdatedDate],
[add_DeletedDate],
[add_IsDeleted],
[add_IsPrimary],
[add_cntm_Id],
[add_alt_No]
)
Values
(
#add_Zip,
#add_FullAddress,
#add_user_Id,
#add_CreatedDate,
#add_UpdatedDate,
#add_DeletedDate,
#add_IsDeleted,
#add_IsPrimary,
#add_cntm_Id,
#add_alt_No
)
END
Below is code behind function:
protected void AddNew(object sender, EventArgs e)
{
try
{
address_MasterBM obj = new address_MasterBM();
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_Zip")).Text != "")
{
String add_Zipstr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_Zip")).Text;
obj.add_Zip = add_Zipstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_FullAddress")).Text != "")
{
String add_FullAddressstr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_FullAddress")).Text;
obj.add_FullAddress = add_FullAddressstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_user_Id")).Text != "")
{
Int32 add_user_Idstr = Convert.ToInt32(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_user_Id")).Text);
obj.add_user_Id = add_user_Idstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_CreatedDate")).Text != "")
{
DateTime add_CreatedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_CreatedDate")).Text);
obj.add_CreatedDate = add_CreatedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_UpdatedDate")).Text != "")
{
DateTime add_UpdatedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_UpdatedDate")).Text);
obj.add_UpdatedDate = add_UpdatedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_DeletedDate")).Text != "")
{
DateTime add_DeletedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_DeletedDate")).Text);
obj.add_DeletedDate = add_DeletedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsDeleted")).Text != "")
{
Boolean add_IsDeletedstr = Convert.ToBoolean(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsDeleted")).Text);
obj.add_IsDeleted = add_IsDeletedstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsPrimary")).Text != "")
{
Boolean add_IsPrimarystr = Convert.ToBoolean(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsPrimary")).Text);
obj.add_IsPrimary = add_IsPrimarystr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_cntm_Id")).Text != "")
{
Int32 add_cntm_Idstr = Convert.ToInt32(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_cntm_Id")).Text);
obj.add_cntm_Id = add_cntm_Idstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_alt_No")).Text != "")
{
String add_alt_Nostr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_alt_No")).Text;
obj.add_alt_No = add_alt_Nostr;
}
obj.Insertaddress_Master();
BindData();
lblException.Text = "";
}
catch(Exception ex)
{
lblException.Text = ex.Message.ToString();
}
}
Below is business method code:
public void Insertaddress_Master() {
try
{
DataAccess obj = new DataAccess();
obj.Provider = EnumProviders.SQLClient;
obj.ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ToString();
ParamStruct[] param = new ParamStruct[10];
param[0].direction = ParameterDirection.Input;
param[0].ParamName = "#add_Zip";
param[0].DataType = DbType.String;
param[0].value = _add_Zip;
param[1].direction = ParameterDirection.Input;
param[1].ParamName = "#add_FullAddress";
param[1].DataType = DbType.String;
param[1].value = _add_FullAddress;
param[2].direction = ParameterDirection.Input;
param[2].ParamName = "#add_user_Id";
param[2].DataType = DbType.Int32;
param[2].value = _add_user_Id;
param[3].direction = ParameterDirection.Input;
param[3].ParamName = "#add_CreatedDate";
param[3].DataType = DbType.DateTime;
param[3].value = _add_CreatedDate;
param[4].direction = ParameterDirection.Input;
param[4].ParamName = "#add_UpdatedDate";
param[4].DataType = DbType.DateTime;
param[4].value = _add_UpdatedDate;
param[5].direction = ParameterDirection.Input;
param[5].ParamName = "#add_DeletedDate";
param[5].DataType = DbType.DateTime;
param[5].value = _add_DeletedDate;
param[6].direction = ParameterDirection.Input;
param[6].ParamName = "#add_IsDeleted";
param[6].DataType = DbType.Boolean;
param[6].value = _add_IsDeleted;
param[7].direction = ParameterDirection.Input;
param[7].ParamName = "#add_IsPrimary";
param[7].DataType = DbType.Boolean;
param[7].value = _add_IsPrimary;
param[8].direction = ParameterDirection.Input;
param[8].ParamName = "#add_cntm_Id";
param[8].DataType = DbType.Int32;
param[8].value = _add_cntm_Id;
param[9].direction = ParameterDirection.Input;
param[9].ParamName = "#add_alt_No";
param[9].DataType = DbType.String;
param[9].value = _add_alt_No;
obj.ExecScalar("Insertaddress_Master", CommandType.StoredProcedure, param);
_returnBoolean = true;
}
catch (DataException ex)
{
_returnBoolean = false;
throw ex;
}
}
when I try to insert data using this code it generates exception saying " Procedure or function Insertaddress_Master has too many arguments specified". Can anyone help solving this problem.
I've read all previous thread on this topic but couldn't find appropriate solution yet.

SqlCommand objCommand = new SqlCommand();
you can recreate this object then it will work.

I got this answer.
You have two fields:
Is Deleted
Is Primarry
You have to passed the boolean that may have true/false.
Try passing 1 for true and 0 for false.
This should do the trick

Related

Returning values from a stored procedure

I have in the database:
ALTER PROCEDURE [dbo].[uspConsumeEnrollments]
(--#File NVARCHAR(300),
#XML XML,
#FamilySent INT = 0 OUTPUT)
AS
BEGIN
SELECT #FamilySent = 755;
Here I am trying to download data:
public int Create(FamilyModel model)
{
try
{
var XML = model.GetEnrolmentFromModel().Serialize();
var RV = -99;
var familySent = 0;
using (var imisContext = new ImisDB())
{
var returnParameter = new SqlParameter("#RV", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;
var xmlParameter = new SqlParameter("#XML", XML);
xmlParameter.DbType = DbType.Xml;
var familySentParameter = new SqlParameter("#FamilySent", SqlDbType.Int);
familySentParameter.Value = 0;
familySentParameter.Direction = ParameterDirection.Output;
var sql = "exec #RV = uspConsumeEnrollments #XML, #FamilySent";
SqlParameter[] myParams = { returnParameter, xmlParameter, familySentParameter };
var result = imisContext.Database.ExecuteSqlCommand(sql, myParams);
RV = (int)returnParameter.Value;
Debug.WriteLine("RV: " + RV);
try
{
familySent = (int)familySentParameter.Value;
}
catch { }
Debug.WriteLine("familySent: " + familySent);
}
return RV;
}
catch (SqlException e)
{
}
}
The reference to the procedure works because I get the RV
I have a problem with FamilySent: I do not get any value.
In the above example I have #FamilySent = 755;
This should be returned and displayed in
Debug.WriteLine("familySent:" + familySent);
but it does not work.
Please try this out :
Modified version of your stored procedure :
ALTER PROCEDURE [dbo].[uspConsumeEnrollments](
--#File NVARCHAR(300),
#XML XML,
#FamilySent INT = 0 OUTPUT
)
AS
BEGIN
SELECT #FamilySent = 755 as FamilySent;
C# code :
public int Create(FamilyModel model)
{
try
{
var XML = model.GetEnrolmentFromModel().Serialize();
var RV = -99;
var familySent = 0;
using (SqlConnection cnx = new SqlConnection(connexionString))
using (SqlCommand cmd = new SqlCommand("[dbo].[uspConsumeEnrollments]", cnx))
{
cmd.CommandType = CommandType.StoredProcedure;
var xmlParameter = new SqlParameter("#XML", XML);
xmlParameter.DbType = DbType.Xml;
cmd.Parameters.Add(xmlParameter);
var familySentParameter = new SqlParameter("#FamilySent", SqlDbType.Int);
familySentParameter.Value = 0;
familySentParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(familySentParameter);
cnx.Open();
List<string[]> res = new List<string[]>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
res.Add(new string[2]{reader.GetName(i),reader[i].ToString());
}
}
}
}
// then here get all of your data you need
if(res.Count > 0){
foreach(string[] s in res){
RV = s[1];
break;
}
}
}
cnx.Close();
return RV;
}
catch (SqlException e)
{
}
}

Invalid format error when inserting data in the database (C# and ASP)

I am missing something but I can't spot it. Below is the error I receive. Most of the input such as the Ticket no, problem number are from session variables. The only input I type in is the Resolution txtbox. Other fields are optional,
Here is my code to insert it where I get my error.
private void InsertResolution()
{
Int32 intRetValue;
intRetValue = clsDatabase.InsertResolution(Convert.ToInt32(chkNoCharge.Checked.ToString()),
Convert.ToInt32(lblTicketNo.Text.Trim().ToString()),
Convert.ToInt32(lblProblemNo.Text.Trim().ToString()),
Convert.ToInt32(lblResolutionEnt.Text.Trim().ToString()),
txtResolution.Text.Trim(), txtDateFixed.Text.Trim().ToString(),
txtDateOnsite.Text.Trim().ToString(),
Convert.ToInt32(drpTechnician.SelectedValue),
Convert.ToDecimal(txtHours.Text.Trim().ToString()),
Convert.ToDecimal(txtCostHours.Text.Trim().ToString()),
Convert.ToDecimal(txtMileage.Text.Trim().ToString()),
Convert.ToDecimal(txtCostMiles.Text.Trim().ToString()),
Convert.ToDecimal(txtSupplies.Text.Trim().ToString()),
Convert.ToDecimal(txtMisc.Text.Trim().ToString()));
if (intRetValue == 0)
{
lblError.Text = "New resolution INSERTED.";
lblResolutionEnt.Text = (int.Parse(lblResolutionEnt.Text) + 1).ToString();
}
else
{
lblError.Text = "Error inserting new resolution.";
}
}
Here is my code in my class
public static Int32 InsertResolution(Int32 intNocharge, Int32 intTicketID, Int32 intIncidentNo, Int32 intResNo, String strResDesc, String strDateFix, String strDateOnsite, Int32 intTechID, Decimal decHours, Decimal decCostHours, Decimal decMileage, Decimal decCostMiles, Decimal decSupplies, Decimal decMisc)
{
SqlConnection cnSQL;
SqlCommand cmdSQL;
Boolean blnErrorOccurred = false; //** set up to false assuming we don't get errors
Int32 intRetCode = 0;
cnSQL = AcquireConnection();
if (cnSQL == null)
{
blnErrorOccurred = true;
}
else
{
//**Build command to execute stored procedure
cmdSQL = new SqlCommand(); //**opening the SqlCommand
cmdSQL.Connection = cnSQL; //** opening the command connection
cmdSQL.CommandType = CommandType.StoredProcedure; //** accessing the stored procedure from the command window
cmdSQL.CommandText = "uspInsertResolution"; //** defining the stored procedure to run
//**taking the input from the string inputting to the database
cmdSQL.Parameters.Add(new SqlParameter("#NoCharge", SqlDbType.Int));
cmdSQL.Parameters["#NoCharge"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#NoCharge"].Value = intNocharge;
//***********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#TicketID", SqlDbType.Int));
cmdSQL.Parameters["#TicketID"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#TicketID"].Value = intTicketID;
//***********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#IncidentNo", SqlDbType.Int));
cmdSQL.Parameters["#IncidentNo"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#IncidentNo"].Value = intIncidentNo;
//***********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#ResNo", SqlDbType.Int));
cmdSQL.Parameters["#ResNo"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#ResNo"].Value = intResNo;
//************************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#ResDesc", SqlDbType.NVarChar, 500));
cmdSQL.Parameters["#ResDesc"].Direction = ParameterDirection.Input;
cmdSQL.Parameters ["#ResDesc"].Value = strResDesc;
//************************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#DateFix", SqlDbType.NVarChar));
cmdSQL.Parameters["#DateFix"].Direction = ParameterDirection.Input;
//**if the field is empty or null
if (String.IsNullOrWhiteSpace(strDateFix))
{
cmdSQL.Parameters["#DateFix"].Value = DBNull.Value;
}
else
{
cmdSQL.Parameters["#DateFix"].Value = Convert.ToDateTime(strDateFix);
}
cmdSQL.Parameters.Add(new SqlParameter("#DateOnsite", SqlDbType.NVarChar));
cmdSQL.Parameters["#DateOnsite"].Direction = ParameterDirection.Input;
//**if the field is empty or null
if (String.IsNullOrWhiteSpace(strDateOnsite))
{
cmdSQL.Parameters["#DateOnsite"].Value = DBNull.Value;
}
else
{
cmdSQL.Parameters["#DateOnsite"].Value = Convert.ToDateTime(strDateOnsite);
}
cmdSQL.Parameters.Add(new SqlParameter("#TechID", SqlDbType.Int));
cmdSQL.Parameters["#TechID"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#TechID"].Value = intTechID;
cmdSQL.Parameters.Add(new SqlParameter("#Hours", SqlDbType.Decimal));
cmdSQL.Parameters["#Hours"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#Hours"].Value = decHours;
cmdSQL.Parameters.Add(new SqlParameter("#Hours", SqlDbType.Decimal));
cmdSQL.Parameters["#Hours"].Direction = ParameterDirection.Input;
cmdSQL.Parameters["#Hours"].Value = decHours;
//********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#Mileage", SqlDbType.Decimal));
cmdSQL.Parameters["#Mileage"].Direction = ParameterDirection.Input;
if (decMileage.ToString() == null)
{
cmdSQL.Parameters["#Mileage"].Value = DBNull.Value;
}
else
{
cmdSQL.Parameters["#Mileage"].Value = decMileage;
}
//*********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#CostMiles", SqlDbType.Decimal));
cmdSQL.Parameters["#CostMiles"].Direction = ParameterDirection.Input;
if (decCostMiles.ToString() == null)
{
cmdSQL.Parameters["#CostMiles"].Value = DBNull.Value;
}
else
{
cmdSQL.Parameters["#CostMiles"].Value = decCostMiles;
}
//*********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#Supplies", SqlDbType.Decimal));
cmdSQL.Parameters["#Supplies"].Direction = ParameterDirection.Input;
if (decSupplies.ToString() == null)
{
cmdSQL.Parameters["#Supplies"].Value = DBNull.Value;
}
else
{
cmdSQL.Parameters["#Supplies"].Value = decSupplies;
}
//*********************************************************************
cmdSQL.Parameters.Add(new SqlParameter("#Misc", SqlDbType.Decimal));
cmdSQL.Parameters["#Misc"].Direction = ParameterDirection.Input;
if (decMisc.ToString() == null)
{
cmdSQL.Parameters["#Misc"].Value = DBNull.Value;
}
else
{
cmdSQL.Parameters["#Misc"].Value = decMisc;
}
//**return the value and display to the page
cmdSQL.Parameters.Add(new SqlParameter("#ErrCode", SqlDbType.Int));
cmdSQL.Parameters["#ErrCode"].Direction = ParameterDirection.ReturnValue;
try
{
intRetCode = cmdSQL.ExecuteNonQuery();
}
catch (Exception ex)
{
blnErrorOccurred = true;
}
finally
{
cmdSQL.Parameters.Clear();
cmdSQL.Dispose();
cnSQL.Close();
cnSQL.Dispose();
}
}
if (blnErrorOccurred)
{
//**if success
return -1;
}
else
{
return 0;
}
}
Here is my stored procedure that I call from my class. I appreciate any input.
CREATE PROCEDURE [dbo].[uspInsertResolution]
#TicketID int,
#IncidentNo int,
#ResNo int,
#ResDesc nvarchar(500),
#DateFix datetime,
#DateOnsite datetime,
#TechID int,
#Hours decimal(10,2),
#Mileage decimal(10,1),
#CostMiles money,
#Supplies money,
#Misc money,
#NoCharge int = 0
AS
--*********************************************************************
--** Add a resolution
--*********************************************************************
SET NOCOUNT ON;
DECLARE #ErrCode int;
IF #NoCharge = 1
INSERT INTO [dbo].[Resolutions] ([TicketID],[IncidentNo],[ResolutionNo],
[ResolutionDesc],[DateFixed],[DateOnsite],[TechnicianID],[Hours],
[CostHours],[Mileage],[CostMiles],[Supplies],[Misc])
VALUES (#TicketID, #IncidentNo, #ResNo, #ResDesc, #DateFix, #DateOnsite,
#TechID, #Hours, 0.0, #Mileage, #CostMiles, #Supplies, #Misc)
ELSE
INSERT INTO [dbo].[Resolutions] ([TicketID],[IncidentNo],[ResolutionNo],
[ResolutionDesc],[DateFixed],[DateOnsite],[TechnicianID],[Hours],
[CostHours],[Mileage],[CostMiles],[Supplies],[Misc])
SELECT #TicketID, #IncidentNo, #ResNo, #ResDesc, #DateFix, #DateOnsite,
#TechID, #Hours, [HRate], #Mileage, #CostMiles, #Supplies, #Misc
FROM [dbo].[Technicians]
WHERE [TechnicianID] = #TechID;
SET #ErrCode = ##ERROR;
SET NOCOUNT OFF;
RETURN #ErrCode;

Oracle + C# Cursor trouble

I have the following code in PowerBuilder (with Oracle as the DB)
DECLARE lcur_pat_q CURSOR FOR
SELECT HL7_MSG
FROM HL7_EXPORT_MSG_Q
WHERE SOCKET_NUM = :al_socket_num
AND (:as_export_level = 'C' OR ACCOUNT_NUM = :gv_acctnum)
AND SUBSTR(HL7_MSG_TYPE, 1, 3) = 'ADT'
ORDER BY HL7_EXPORT_MSG_Q_NUM
FOR UPDATE OF HL7_EXPORT_MSG_Q_NUM;
OPEN lcur_pat_q;
How can I rewrite this cursor in C#?
This variant
var dbCmd_lcur_pat_q = new OracleCommand();
dbCmd_lcur_pat_q.CommandText = "SELECT HL7_MSG, HL7_EXPORT_MSG_Q_NUM " +
" FROM HL7_EXPORT_MSG_Q " +
" WHERE SOCKET_NUM = :al_socket_num " +
" AND (:as_export_level = 'C' OR ACCOUNT_NUM = :gv_acctnum) " +
" AND SUBSTR(HL7_MSG_TYPE, 1, 3) = 'ADT' " +
"ORDER BY HL7_EXPORT_MSG_Q_NUM";
dbCmd_lcur_pat_q.Parameters.Add("al_socket_num", OracleDbType.Int32);
dbCmd_lcur_pat_q.Parameters["al_socket_num"].Value = al_socket_num ?? (object)DBNull.Value;
dbCmd_lcur_pat_q.Parameters.Add("as_export_level", OracleDbType.NVarchar2);
dbCmd_lcur_pat_q.Parameters["as_export_level"].Value = as_export_level ?? (object)DBNull.Value;
dbCmd_lcur_pat_q.Parameters.Add("gv_acctnum", OracleDbType.Int32);
dbCmd_lcur_pat_q.Parameters["gv_acctnum"].Value = AppGlobalVariables.gv_acctnum ?? (object)DBNull.Value;
dbCmd_lcur_pat_q.CommandType = CommandType.Text;
var lcur_pat_q = AppGlobalVariables.sqlca.ExecuteReader(dbCmd_lcur_pat_q);
returns empty variable lcur_pat_q
The code of ExecuteReader:
public OracleDataReader ExecuteReader(OracleCommand command)
{
try
{
if (_connection == null)
_connection = InitializeConnection();
if (_transaction == null)
_transaction = _connection.BeginTransaction();
command.Connection = _connection;
command.Transaction = _transaction;
sqlcode = 0;
sqlerrtext = String.Empty;
command.CommandTimeout = 30;
command.BindByName = true;
var reader = command.ExecuteReader();
if (reader == null) return null;
if (!reader.HasRows)
sqlcode = 100;
return reader;
}
catch (OracleException e)
{
sqlcode = e.ErrorCode;
sqlerrtext = e.Message;
Debug.Print("{0}: {1}", sqlcode, sqlerrtext);
return null;
}
catch (Exception e)
{
sqlcode = -999;
sqlerrtext = e.Message;
Debug.Print("{0}: {1}", sqlcode, sqlerrtext);
return null;
}
}
I have no idea how to do this and need help.

Insert Query in C# using Parameters

Am trying to insert several columns into my database using the following insert query from C# but it throws the exception somehow somewhere and my guess is there are no values provided for insertion. i just want to confirm that and find out how i can fix the insert statement. i have a picture below that displays what is passed into the parameters at runtime. i used a break point to get this info.
need your expertise at this one...thanks
if (Page.IsValid)
{
DateTime exhibitDate = DateTime.Now;
int caseid = Convert.ToInt32(CaseIDDropDownList.SelectedItem.Text);
string exhibittype = exhibitTypeTextBox.Text.ToString();
string storedloc = storedLocationTextBox.Text.ToString();
string offid = DropDownList1.SelectedItem.Text.ToString();
Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
try
{
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (#CaseID, #ExhibitType, #ExhibitImage, #DateReceived, #StoredLocation, #InvestigationStatus, #OfficerID, #SuspectID, #InvestigatorID, #ManagerID, #AdminID)", connections);
SqlParameter param0 = new SqlParameter("#CaseID", SqlDbType.Int);
param0.Value = caseid;
command.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter("#ExhibitType", SqlDbType.NText);
param1.Value = exhibittype;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("#ExhibitImage", SqlDbType.Image);
param2.Value = imgBinaryData;
command.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#DateReceived", SqlDbType.SmallDateTime);
param3.Value = exhibitDate;
command.Parameters.Add(param3);
SqlParameter param4 = new SqlParameter("#StoredLocation", SqlDbType.NText);
param4.Value = storedloc;
command.Parameters.Add(param4);
SqlParameter param5 = new SqlParameter("#InvestigationStatus", SqlDbType.VarChar, 50);
param5.Value = "";
command.Parameters.Add(param5);
SqlParameter param6 = new SqlParameter("#OfficerID", SqlDbType.NChar, 10);
param6.Value = offid;
command.Parameters.Add(param6);
SqlParameter param7 = new SqlParameter("#SuspectID", SqlDbType.NChar, 10);
param7.Value = null;
command.Parameters.Add(param7);
SqlParameter param8 = new SqlParameter("#InvestigatorID", SqlDbType.NChar, 10);
param8.Value = null;
command.Parameters.Add(param8);
SqlParameter param9 = new SqlParameter("#ManagerID", SqlDbType.NChar, 10);
param9.Value = null;
command.Parameters.Add(param9);
SqlParameter param10 = new SqlParameter("#AdminID", SqlDbType.NChar, 10);
param10.Value = adminID;
command.Parameters.Add(param10);
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
CaseIDDropDownList.ClearSelection();
exhibitTypeTextBox.Text = null;
storedLocationTextBox.Text = null;
DropDownList1.ClearSelection();
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
the exception is as follows
$exception {"The parameterized query '(#CaseID int,#ExhibitType ntext,#ExhibitImage image,#DateReceive' expects the parameter '#SuspectID', which was not supplied."} System.Exception {System.Data.SqlClient.SqlException}
If you want to pass in NULL for your database / parameter type, you need to use DBNull.Value like this:
SqlParameter param9 = new SqlParameter("#ManagerID", SqlDbType.NChar, 10);
param9.Value = DBNull.Value;
command.Parameters.Add(param9);
Do this wherever you're setting something to null right now, and I'm pretty sure it'll work just fine. Everything is looking okay.
You can do this much easier, try it as such:
if (Page.IsValid)
{
DateTime exhibitDate = DateTime.Now;
int caseid = Convert.ToInt32(CaseIDDropDownList.SelectedItem.Text);
string exhibittype = exhibitTypeTextBox.Text.ToString();
string storedloc = storedLocationTextBox.Text.ToString();
string offid = DropDownList1.SelectedItem.Text.ToString();
Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
try
{
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (#CaseID, #ExhibitType, #ExhibitImage, #DateReceived, #StoredLocation, #InvestigationStatus, #OfficerID, #SuspectID, #InvestigatorID, #ManagerID, #AdminID)", connections);
command.Parameters.AddWithValue("#CaseID", caseid);
//and so on for your 10 parameters
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
CaseIDDropDownList.ClearSelection();
exhibitTypeTextBox.Text = null;
storedLocationTextBox.Text = null;
DropDownList1.ClearSelection();
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
}
I'm not sure if this will actually fix what is happening without knowing the exact exception. If you could provide the actual exception that would help a lot.

unable to update gridview

Please help ,i have added update/edit command button in gridview so to update data in my sql server database but am unable to do it. Data is not updated in database .
======code for onrowupdate========================================
protected void gRowUpdate(object sender, GridViewUpdateEventArgs e)
{
Books b = null;
b = new Books();
DataTable dt=null;
GridView g = (GridView)sender;
try
{ dt=new DataTable();
b = new Books();
b.author = Convert.ToString(g.Rows[e.RowIndex].FindControl("Author"));
b.bookID = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("BookID"));
b.title = Convert.ToString(g.Rows[e.RowIndex].FindControl("Title"));
b.price = Convert.ToDouble(g.Rows[e.RowIndex].FindControl("Price"));
// b.rec = Convert.ToString(g.Rows[e.RowIndex].FindControl("Date_of_reciept"));
b.ed = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.bill = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.cre_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.src = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.pages = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("Edition"));
b.pub = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.mod_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.remark = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
// b.year = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition"));
b.updatebook(b);
g.EditIndex = -1;
dt = b.GetAllBooks();
g.DataSource = dt;
g.DataBind();
}
catch (Exception ex)
{
throw (ex);
}
finally
{
b = null;
}
}
===================My stored procedure for update book able to update database by exec in sqlserver mgmt studio==========================
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[usp_updatebook]
#bookid bigint,
#author varchar(50),
#title varchar(50),
#price bigint,
#src_equisition varchar(50),
#bill_no varchar(50),
#publisher varchar(50),
#pages bigint,
#remark varchar(50),
#edition varchar(50),
#created_by varchar(50),
#modified_by varchar(50)
/#date_of_reciept datetime,
#year_of_publication datetime/
AS
declare
#modified_on datetime
set #modified_on=getdate()
UPDATE books
SET
author=#author,
title=#title,
price=#price,
src_equisition=#src_equisition,
bill_no=#bill_no,
publisher=#publisher,
/Date_of_reciept=#date_of_reciept,/
pages=#pages,
remark=#remark,
edition=#edition,
/Year_of_publication=#year_of_publication,/
created_by=#created_by,
modified_on=#modified_on,
modified_by=#modified_by
WHERE bookid=#bookid
========================class library function for update====================
public void updatebook(Books b)
{
DataAccess dbAccess = null;
SqlCommand cmd = null;
try
{
dbAccess = new DataAccess();
cmd = dbAccess.GetSQLCommand("usp_updatebook", CommandType.StoredProcedure);
cmd.Parameters.Add("#bookid", SqlDbType.VarChar, 50).Value = b.bookID;
cmd.Parameters.Add("#author", SqlDbType.VarChar, 50).Value = b.author;
cmd.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = b.title;
cmd.Parameters.Add("#price", SqlDbType.Money).Value = b.price;
cmd.Parameters.Add("#publisher", SqlDbType.VarChar, 50).Value = b.pub;
// cmd.Parameters.Add("#year_of_publication", SqlDbType.DateTime).Value =Convert.ToDateTime( b.year);
cmd.Parameters.Add("#src_equisition", SqlDbType.VarChar, 50).Value = b.src;
cmd.Parameters.Add("#bill_no", SqlDbType.VarChar, 50).Value = b.bill;
cmd.Parameters.Add("#remark", SqlDbType.VarChar, 50).Value = b.remark;
cmd.Parameters.Add("#pages", SqlDbType.Int).Value = b.pages;
cmd.Parameters.Add("#edition", SqlDbType.VarChar, 50).Value = b.ed;
// cmd.Parameters.Add("#date_of_reciept", SqlDbType.DateTime).Value = Convert.ToDateTime(b.rec);
// cmd.Parameters.Add("#created_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.cre_on);
cmd.Parameters.Add("#created_by", SqlDbType.VarChar, 50).Value = b.cre_by;
//cmd.Parameters.Add("#modified_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.mod_on);
cmd.Parameters.Add("#modified_by", SqlDbType.VarChar, 50).Value = b.mod_by;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Open)
cmd.Connection.Close();
dbAccess = null;
cmd = null;
}
}
I have also tried to do update by following way
protected void gv1_updating(object sender, GridViewUpdateEventArgs e)
{
GridView g = (GridView)sender;
abc a = new abc();
DataTable dt = new DataTable();
try
{
a.cd_Id = Convert.ToInt32(g.DataKeys[e.RowIndex].Values[0].ToString());
//TextBox b = (TextBox)g.Rows[e.RowIndex].Cells[0].FindControl("cd_id");
TextBox c = (TextBox)g.Rows[e.RowIndex].Cells[2].FindControl("cd_name");
TextBox d = (TextBox)g.Rows[e.RowIndex].Cells[3].FindControl("version");
TextBox f = (TextBox)g.Rows[e.RowIndex].Cells[4].FindControl("company");
TextBox h = (TextBox)g.Rows[e.RowIndex].Cells[6].FindControl("created_by");
TextBox i = (TextBox)g.Rows[e.RowIndex].Cells[8].FindControl("modified_by");
//a.cd_Id = Convert.ToInt32(b.Text);
a.cd_name = c.Text;
a.ver = d.Text;
a.comp = f.Text;
a.cre_by = h.Text;
a.mod_by = i.Text;
a.updateDigi(a);
g.EditIndex = -1;
dt = a.GetAllDigi();
g.DataSource = dt;
g.DataBind();
}
catch(Exception ex)
{
throw (ex);
}
finally
{
dt = null;
a = null;
g = null;
}
}
=================== but have error of Index out of range exception=========
please do reply,thanxs in advance
The IndexOutOfRangeException is probably due to this code:
a.cd_Id = Convert.ToInt32(g.DataKeys[e.RowIndex].Values[0].ToString());
TextBox c = (TextBox)g.Rows[e.RowIndex].Cells[2].FindControl("cd_name");
TextBox d = (TextBox)g.Rows[e.RowIndex].Cells[3].FindControl("version");
TextBox f = (TextBox)g.Rows[e.RowIndex].Cells[4].FindControl("company");
TextBox h = (TextBox)g.Rows[e.RowIndex].Cells[6].FindControl("created_by");
TextBox i = (TextBox)g.Rows[e.RowIndex].Cells[8].FindControl("modified_by");
More precisely the part where the indexing is occurring. Are you sure that you have 9 Cells
(indexes 0 to 8) ?

Categories

Resources