Scalar Variable #AssetNumber - c#

When i step through the code the parameter is being added, its just when the sql command is executed, it throws this error up
public static DataTable GetPostings2(string AssetNumberV, string PeriodFromV, string PeriodToV)
{
DataTable dtGetPostings2;
try
{
dtGetPostings2 = new DataTable("GetPostings");
SqlParameter AssetNumber = new SqlParameter("#AssetNumber", SqlDbType.VarChar, 6);
AssetNumber.Value = AssetNumberV;
SqlParameter PeriodFrom = new SqlParameter("#PeriodFrom", SqlDbType.VarChar, 6);
PeriodFrom.Value = PeriodFromV;
SqlParameter PeriodTo = new SqlParameter("#PeriodTo", SqlDbType.VarChar, 6);
PeriodTo.Value = PeriodToV;
SqlCommand scGetPostings2 = new SqlCommand("SELECT * FROM [POSTING] WHERE [ASSET_NO] = #AssetNumber And PERIOD >= #PeriodFrom AND PERIOD <= #PeriodTo ORDER by PERIOD, JOUR_REF, JOUR_LINE", DataAccess.AssetConnection);
SqlDataAdapter sdaGetPostings2 = new SqlDataAdapter();
sdaGetPostings2.SelectCommand = scGetPostings2;
sdaGetPostings2.Fill(dtGetPostings2);
return dtGetPostings2;
}
catch (Exception ex)
{
MessageBox.Show("Error Retriving Posting Details: Processed with this error:" + ex.Message);
return null;
}
}

The code listed does not add the parameters to the SqlCommand.Parameters collection. For example:
SqlCommand scGetPostings2 = new SqlCommand("SELECT * FROM [POSTING] WHERE [ASSET_NO] = #AssetNumber And PERIOD >= #PeriodFrom AND PERIOD <= #PeriodTo ORDER by PERIOD, JOUR_REF, JOUR_LINE", DataAccess.AssetConnection);
scGetPostings2.Parameters.Add(AssetNumber);
scGetPostings2.Parameters.Add(PeriodFrom );
scGetPostings2.Parameters.Add(PeriodTo );
// Code continues as above
SqlDataAdapter sdaGetPostings2 = new SqlDataAdapter();
// And so on

Related

Easier way to get data from the CSV file and substitute data from other tables in columns with foreign key

Anyone can help? All day I can not understand why I get an error.
Error is:
SqlParameter with ParameterName '#FKTO' is not included in SqlParameterCollection
Maybe there is an easier way to get data from the CSV file and substitute data from other tables in columns with foreign key.
private void insertInTab()
{
try
{
sqlConnection = new SqlConnection(ConnectionMSSQLServer);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
const string strQueryRechnung = #"IF NOT EXISTS (SELECT Menge, Einheit, BetragBrutto, Beginn, Ende, tblFkto.IdFKTO AS IdF, tblGeraet.Id_Geraet AS IdG
FROM tblRechnung, tblFkto, tblGeraet
WHERE
tblFkto.FKTO = #FKTO
AND tblGeraet.Bezeichnung = #Bezeichnung
AND Menge = #Menge
AND Einheit = #Einheit
AND BetragBrutto = #BetragBrutto
AND Beginn = #Beginn
AND Ende = #Ende)
INSERT INTO tblRechnung (Menge, Einheit, BetragBrutto, Beginn, Ende, IdFKTO, IdGeraet)
VALUES (#Menge, #Einheit, #BetragBrutto, #Beginn, #Ende, tblFkto.IdFKTO, tblGeraet.Id_Geraet);";
using (sqlCommand = new SqlCommand(strQueryRechnung, sqlConnection))
{
sqlCommand.Parameters.Add("#tblFkto.IdFKTO", SqlDbType.Int);
sqlCommand.Parameters.Add("#blGeraet.Id_Geraet", SqlDbType.Int);
sqlCommand.Parameters.Add("#Menge", SqlDbType.Int);
sqlCommand.Parameters.Add("#Einheit", SqlDbType.NVarChar, 50);
sqlCommand.Parameters.Add("#BetragBrutto", SqlDbType.SmallMoney);
sqlCommand.Parameters.Add("#Beginn", SqlDbType.DateTime);
sqlCommand.Parameters.Add("#Ende", SqlDbType.DateTime);
sqlConnection.Open();
for (int i = 2; i < dgvCSVRechnung.Rows.Count; i++)
{
sqlCommand.Parameters["#FKTO"].Value = dgvCSVRechnung.Rows[i].Cells[0].Value;
sqlCommand.Parameters["#Bezeichnung"].Value = dgvCSVRechnung.Rows[i].Cells[2].Value;
sqlCommand.Parameters["#Menge"].Value = Int32.Parse((string)dgvCSVRechnung.Rows[i].Cells[3].Value);
sqlCommand.Parameters["#Einheit"].Value = dgvCSVRechnung.Rows[i].Cells[4].Value;
sqlCommand.Parameters["#BetragBrutto"].Value = Decimal.Parse((string)dgvCSVRechnung.Rows[i].Cells[5].Value);
sqlCommand.Parameters["#Beginn"].Value = DateTime.ParseExact(dgvCSVRechnung.Rows[i].Cells[6].Value.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
sqlCommand.Parameters["#Ende"].Value = DateTime.ParseExact(dgvCSVRechnung.Rows[i].Cells[7].Value.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
sqlCommand.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

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.

Specified cast is not valid issue

My code checks for changes in the database and then sends an update via a web service to the client.
I had the part sending the message to the client working fine because making the calls to check for changes in the database. Now that I have added the portion checking database changes I am getting the following error.
When Debugging my code the error points at the exception at the very bottom of the code so I have no idea where the error is coming from and no way of fixing it.
Any advise would be greatly appreciated
SendInvUpdate.InvServices.UpdateRatePackagesRequest ur = new SendInvUpdate.InvServices.UpdateRatePackagesRequest();
SendInvUpdate.InvServices.UpdateRatePackagesOperationResponse or = new SendInvUpdate.InvServices.UpdateRatePackagesOperationResponse();
protected void Page_Load(object sender, EventArgs e)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["bb"].ConnectionString;
SqlConnection Con = new SqlConnection(connStr);
Con.Open();
SqlCommand cmd = new SqlCommand("invpush_PollForAvailableChanges", Con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter NewSysChangeVersionParam = new SqlParameter("#NewSysChangeVersion", SqlDbType.Int);
NewSysChangeVersionParam.Value = (object)NewSysChangeVersionParam ?? DBNull.Value;
NewSysChangeVersionParam.Direction = ParameterDirection.InputOutput;
NewSysChangeVersionParam.SqlDbType = SqlDbType.BigInt;
SqlDataReader sdr = cmd.ExecuteReader();
InventoryPushSubscriptionRecord rec = new InventoryPushSubscriptionRecord();
while (sdr.Read())
{
rec.InventoryPushSubId = sdr.GetInt32(0);
rec.CMName = sdr.GetString(1);
rec.NotifUrl = sdr.GetString(2);
rec.Options = sdr.GetString(3);
rec.LastSysChangeVersion = sdr.IsDBNull(4)?(long?)null:sdr.GetInt32(4);
}
if(!sdr.NextResult()) throw new System.Exception("Expected Result set 1 for InventoryChangeRecord");
InventoryChangeRecord inrec = new InventoryChangeRecord();
while (sdr.Read())
{
inrec.InventoryPushSubId= sdr.GetInt32(0);
inrec.SysChangeVersion=sdr.IsDBNull(1)?(long?)null:sdr.GetInt32(1);
inrec.InvDate=sdr.GetDateTime(2);
inrec.ResId=sdr.GetInt32(3);
inrec.RoomType=sdr.GetString(4);
inrec.InvCount=sdr.GetInt32(5);
inrec.ResName=sdr.GetString(6);
}
sdr.Close();
sdr.Dispose();
if (NewSysChangeVersionParam != null)
{
int ResId;
Int64 ResoId;
ResortId = inrec.ResId;
SqlDataAdapter sda = new SqlDataAdapter("Select BID,RId from BBTest.bbtest.tblResMapping where BId=#ResId",Con);
SqlParameter resId = new SqlParameter("#ResId", ResId);
sda.SelectCommand.Parameters.Add(resId);
DataSet ds = new DataSet();
sda.Fill(ds, "tblresmapping");
if (ds.Tables[0].Rows.Count > 0)
{
ResoId = Convert.ToInt32(ds.Tables[0].Rows[0]["ResonlineId"]);
}
if (ds.Tables[0].Rows.Count != 0)
{
Int64 RatePackageId;
SqlDataAdapter sqlda = new SqlDataAdapter("Select BId,BBRoom,ResRatePackageID from tblResRatePackages where BID =#ResortId", Con);
SqlParameter resI = new SqlParameter("#RId", resId);
sqlda.SelectCommand.Parameters.Add(resI);
DataSet dt = new DataSet();
sqlda.Fill(dt, "tblResRatePackages");
if (dt.Tables[0].Rows.Count > 0)
{
RatePackageId = Convert.ToInt64(dt.Tables[0].Rows[0]["ResRatePackageID"]);
Int64 HID = ResId;
Int64 HRID = RatePackageId;
SendInvUpdate.InvServices.UpdateRatePackagesRequest request = new SendInvUpdate.InvServices.UpdateRatePackagesRequest();
request.HotelId = account.HotelId;
int avail = inrec.InvCount;
DateTime frodte = inrec.InvDate;
int NoofRatePackages = 3;
UpdateRatePackageRequest[] RatePackages = new UpdateRatePackageRequest[NoofRatePackages];
string res;
request.RatePackages = new UpdateRatePackageRequest[NoofRatePackages];
request.RatePackages = RatePackages;
for (int i = 0; i < NoofRatePackages; i++)
{
UpdateRatePackageRequest rp = new UpdateRatePackageRequest();
request.RatePackages[i] = rp;
rp.RatePackageId = HRID;
rp.Rates = new RateDetails[NoofRatePackages];
for (int j = 0; j < NoofRatePackages; j++)
{
RateDetails rd = new RateDetails();
rp.Rates[j] = rd;
rd.Availability = avail;
rd.AvailabilityApplicationType = SendInvUpdate.InvServices.AvailabilityApplicationType.SET;
rd.FromDate = frodte;
// rd.ToDate = todte;
}
}
SendInvUpdate.InvServices.InventoryServiceClient isc = new SendInvUpdate.InvServices.InventoryServiceClient();
or = isc.UpdateRatePackages(request);
res = or.Results.ToString();
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
You're hiding your real exception stack trace by catching the exception and throwing it again like you're doing;
try {
...
}
catch(Exception ex) // catch all exceptions
{
throw ex; // throw the same exception, removing the old stack trace
}
Either you should just remove the whole try/catch, or change to;
try {
...
}
catch(Exception ex) // catch all exceptions
{
throw; // throw the last caught exception, keeping the stack trace
}
and you will suddenly be able to see the exact location of your original exception. I'm sure you will find your error right away.
In my case, getting this error message, Oracle turned out to be returning an irrational number.
My code was throwing the "Specified cast is not valid" exception at adapter.Fill(ds);.NET was not interpreting the returned number correctly with the code I had been using. The addition of the line adapter.ReturnProviderSpecificTypes = true; Made it possible for .NET to interpret the number, rounded to the Nth decimal (last digit rounded up from 3 to 4 for some reason...): 2.25000000000000333333333333333333333334
private static DataSet dataset_test(string sql)
{
DataSet ds = new DataSet();
using (OracleConnection objConn = new OracleConnection(connectionstring))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = sql;
objCmd.CommandType = CommandType.Text;
try
{
objConn.Open();
OracleDataAdapter adapter = new OracleDataAdapter(objCmd);
adapter.ReturnProviderSpecificTypes = true;
adapter.Fill(ds);
}
catch (Exception)
{
throw;
}
objConn.Close();
return ds;
}
}
One thing to try: Set a breakpoint right at the start of the try-catch block, on the connStr = line, and step through the code line by line, progressing over method calls. In this way you can quickly track down which part of the code is throwing the error, and then home in on that point to look for the specific problem. (You will also be able to read the original exception and innerexception messages prior to the rethrow.)
Given the title of your question, so the assumption that the error you are having is a casting exception, the first place I would check would be in your database data retrieval code. You are using sdr.GetInt32(0) for instance, this would throw that sort of error if column 0 couldn't be converted to an integer.
Hope this helps. If you are able to track down more information, post it and we'll see if we can give more specific advice.

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