unable to update gridview - c#

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) ?

Related

why i got the error "Input string was not in a correct format"

I am inserting data from datagridview into database , I debug my code and found the error Input string was not in a correct format. in the following line
Convert.ToInt32(dgvResult.Rows[i].Cells[9].Value.ToString())
this column is an integer column and when i replaced this line with integer value for example number 3 insert completed without errors , and the other integer columns also inserted same way without any error
this is my code :
if (checkApproveResult.Checked == false && chkupdateApproved.Checked == false)
{
for (int i = 0; i < dgvResult.Rows.Count; i++)
{
result.UPDATE_LAB_RESULTS(Convert.ToInt32(txtOrder.Text),
dgvResult.Rows[i].Cells[7].Value.ToString(),
5,
dgvResult.Rows[i].Cells[6].Value.ToString(),
txtExamUser.Text,
DateTime.Parse(DateTimeExamined.Value.ToString()),
Convert.ToInt32(dgvResult.Rows[i].Cells[2].Value),
dgvResult.Rows[i].Cells[4].Value.ToString(),
dgvResult.Rows[i].Cells[5].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[9].Value.ToString()),
Convert.ToInt32(txtPno.Text),
Convert.ToInt32(txtcustid.Text),
txtReqForm.Text,
dgvResult.Rows[i].Cells[1].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[8].Value.ToString()));
}
MessageBox.Show("Result Saved Successfully ", "Entering Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (chkupdateApproved.Checked == true)
{
for (int i = 0; i < dgvResult.Rows.Count; i++)
{
result.ADD_LAB_RESULTS_UPDATES(Convert.ToInt32(txtsampleid.Text),
Convert.ToInt32(txtOrder.Text),
Convert.ToInt32(dgvResult.Rows[i].Cells[2].Value),
Convert.ToInt32(txtgroupid.Text),
"YES",
6,
dgvResult.Rows[i].Cells[11].Value.ToString(),
DateTime.Parse(DateTimeExamined.Value.ToString()),
dgvResult.Rows[i].Cells[13].Value.ToString(),
DateTime.Parse(dateTimeApprove.Value.ToString()),
dgvResult.Rows[i].Cells[4].Value.ToString(),
dgvResult.Rows[i].Cells[5].Value.ToString(),
dgvResult.Rows[i].Cells[6].Value.ToString(),
Convert.ToInt32(txtpackageid.Text),
Convert.ToInt32(dgvResult.Rows[i].Cells[9].Value.ToString()),
2,
Convert.ToInt32(txtPno.Text),
Convert.ToInt32(txtcustid.Text), txtReqForm.Text,
Convert.ToInt32(dgvResult.Rows[i].Cells[8].Value.ToString()),
txtupdatedby.Text,
DateTime.Parse(dateupdate.Value.ToString()));
}
update.UPDATE_LAB_RESULT_STATUS(Convert.ToInt32(txtOrder.Text), Convert.ToInt32(txtsampleid.Text), 2);
MessageBox.Show("Result Updated Successfully ", "Update Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
And the code for ADD_LAB_RESULT_UPDATES was :
public void ADD_LAB_RESULTS_UPDATES(int SAMPLE_ID, int ORDER_ID,int TESTID,int GROUPID, string NORMAL_RESULT,
int SAMPLE_STATUS,string EXAMINED_BY,DateTime EXAMINED_DATE, string APPROVED_BY, DateTime APPROVED_DATE,
string RESULT_NUMBER, string RESULT_REPORT, string RESULT_NOTE,int packageid, int machine_id, int deptid,
int patient_no, int custid, string REQ_FORM_NO,int serial,string UPDATED_BY,DateTime UPDATED_DATE)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.open();
SqlParameter[] param = new SqlParameter[22];
param[0] = new SqlParameter("#SAMPLE_ID", SqlDbType.Int);
param[0].Value = SAMPLE_ID;
param[1] = new SqlParameter("#ORDER_ID", SqlDbType.Int);
param[1].Value = ORDER_ID;
param[2] = new SqlParameter("#TESTID", SqlDbType.Int);
param[2].Value = TESTID;
param[3] = new SqlParameter("#GROUPID", SqlDbType.Int);
param[3].Value = GROUPID;
param[4] = new SqlParameter("#NORMAL_RESULT", SqlDbType.VarChar, 10);
param[4].Value = NORMAL_RESULT;
param[5] = new SqlParameter("#SAMPLE_STATUS", SqlDbType.Int);
param[5].Value = SAMPLE_STATUS;
param[6] = new SqlParameter("#EXAMINED_BY", SqlDbType.VarChar, 50);
param[6].Value = EXAMINED_BY;
param[7] = new SqlParameter("#EXAMINED_DATE", SqlDbType.DateTime);
param[7].Value = EXAMINED_DATE;
param[8] = new SqlParameter("#APPROVED_BY", SqlDbType.VarChar, 50);
param[8].Value = APPROVED_BY;
param[9] = new SqlParameter("#APPROVED_DATE", SqlDbType.DateTime);
param[9].Value = APPROVED_DATE;
param[10] = new SqlParameter("#RESULT_NUMBER", SqlDbType.VarChar, 50);
param[10].Value = RESULT_NUMBER;
param[11] = new SqlParameter("#RESULT_REPORT", SqlDbType.VarChar, 2000);
param[11].Value = RESULT_REPORT;
param[12] = new SqlParameter("#RESULT_NOTE", SqlDbType.VarChar, 200);
param[12].Value = RESULT_NOTE;
param[13] = new SqlParameter("#packageid", SqlDbType.Int);
param[13].Value = packageid;
param[14] = new SqlParameter("#machine_id", SqlDbType.Int);
param[14].Value = machine_id;
param[15] = new SqlParameter("#deptid", SqlDbType.Int);
param[15].Value = deptid;
param[16] = new SqlParameter("#patient_no", SqlDbType.Int);
param[16].Value = patient_no;
param[17] = new SqlParameter("#custid", SqlDbType.Int);
param[17].Value = custid;
param[18] = new SqlParameter("#REQ_FORM_NO", SqlDbType.VarChar, 50);
param[18].Value = REQ_FORM_NO;
param[19] = new SqlParameter("#serial", SqlDbType.Int);
param[19].Value = serial;
param[20] = new SqlParameter("#UPDATED_BY", SqlDbType.VarChar, 50);
param[20].Value = UPDATED_BY;
param[21] = new SqlParameter("#UPDATED_DATE", SqlDbType.DateTime);
param[21].Value = UPDATED_DATE;
DAL.ExecuteCommand("ADD_LAB_RESULTS_UPDATES", param);
DAL.close();
}
the error with parameter 14 machine_id
also the table in the database machine_id int.
What is the error ?
More information I have first if statement (update statement)
result. UPDATE_LAB_RESULTS includes same parameter machine_id and its working and inserting without errors.
Second if statement (insert statement) and show the error with machine_id parameter.
You have to check the following :
1- check the parameter list variables types (string , int , ...) and compare it with your procedure you will find one variable type different in the stored procedure integer and in the parameter list string.

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;

Procedure or function has too many arguments specified

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

How to implement Edit Feature in asp.net application?

Below 2 links give the preview of my sample application.
http://img812.imageshack.us/i/image1adl.jpg/ : shows mine sample application. All fields are self explanatory (if query, let me know)
http://img834.imageshack.us/i/image2vc.jpg/ : shows, when clicked the "Edit" button from the grid, the timings are shown correctly but the order gets disturbed. (See 7:00 coming on the top and then the timings list are seen).
My Questions
How to correct the timings problem? (Link # 2)
Code for "Edit" is below
protected void lnkEdit_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt16((sender as Button).CommandArgument);
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE IsDeleted=0 and Imageid='"+ imageid +"'";
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtImageName.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
chkIsActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"].ToString());
ddlStartTime.DataSource = ds;
ddlStartTime.DataTextField = ds.Tables[0].Columns["StartTime"].ColumnName.ToString();
ddlStartTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlStartTime.DataBind();
ddlEndTime.DataSource = ds;
ddlEndTime.DataTextField = ds.Tables[0].Columns["EndTime"].ColumnName.ToString();
ddlEndTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlEndTime.DataBind();
BindDropDownList();
IsEdit = true;
}
When i edit the existing record in the grid, i am getting the values, but the record is not being updated but added as a new record into db. I am aware that i am suppose to write update script. But where to write that?
Below the code is for the same;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string strImageName = txtImageName.Text.ToString();
int IsActive = 1;
if (chkIsActive.Checked)
IsActive = 1;
else
IsActive = 0;
string startDate = ddlStartTime.SelectedItem.Text;
string endDate = ddlEndTime.SelectedItem.Text;
if ( Convert.ToDateTime(endDate) - Convert.ToDateTime(startDate) > new TimeSpan(2, 0, 0) || Convert.ToDateTime(endDate)- Convert.ToDateTime(startDate) < new TimeSpan(2,0,0))
{
//Response.Write(#"<script language='javascript'> alert('Difference between Start Time and End Time is 2 hours'); </script> ");
lblHours.Visible = true;
lblHours.Text = "Difference between Start Time and End Time should be 2 hours";
return;
}
if (checkConflictTime())
{
lblMessage.Visible = true;
lblMessage.Text = "Time Conflict";
return;
}
//if (checkTimeBetween())
//{
//}
if (fuFileUpload.PostedFile != null && fuFileUpload.PostedFile.FileName != "")
{
lblHours.Visible = false;
byte[] imageSize = new Byte[fuFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadedImage = fuFileUpload.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)fuFileUpload.PostedFile.ContentLength);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
SqlCommand cmd = new SqlCommand();
if (IsEdit == false)
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconn;
SqlParameter ImageName = new SqlParameter("#img_name", SqlDbType.NVarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter ActualImage = new SqlParameter("#img_content", SqlDbType.VarBinary);
ActualImage.Value = imageSize;
cmd.Parameters.Add(ActualImage);
SqlParameter DeletedImage = new SqlParameter("#IsDeleted", SqlDbType.Bit);
DeletedImage.Value = 0;
cmd.Parameters.Add(DeletedImage);
SqlParameter IsActiveCheck = new SqlParameter("#IsActive", SqlDbType.Bit);
IsActiveCheck.Value = IsActive;
cmd.Parameters.Add(IsActiveCheck);
SqlParameter StartDate = new SqlParameter("#StartTime", SqlDbType.NVarChar, 100);
StartDate.Value = startDate;
cmd.Parameters.Add(StartDate);
SqlParameter EndDate = new SqlParameter("#EndTime", SqlDbType.NVarChar, 100);
EndDate.Value = endDate;
cmd.Parameters.Add(EndDate);
sqlconn.Open();
int result = cmd.ExecuteNonQuery();
sqlconn.Close();
if (result > 0)
{
lblMessage.Visible = true;
lblMessage.Text = "File Uploaded!";
gvImages.DataBind();
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
}
Please help!
Where do you define Bool/Bolean IsEdit? I think its value is reset on page postback, that's why it is always false and the record is being inserted. I would suggest you to use a hidden field to track this and set its value there and check the value upon insert/updating. Finally it will be something like...
if (ds.Tables[0].Rows.Count > 0)
{
//your code
hiddenField.Value = "true"; // you can set default value to false
}
and then after
if (hiddenField.Value == "false")
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}

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.

Categories

Resources