I have some problem in my code( in our sql database UnitPrice and TotalPrice data type decimal and when I want to add data I got this error
"error converting data type varchar to numeric"
my code:
#region EDIT RECORD
private bool EditRecord()
{
DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
if (row == null) return false;
PopupChillers frm = new PopupChillers();
frm.InitData(this.FindForm(), gridControl3, gridView1, row);
bool ret = frm.ShowDialog() == DialogResult.OK;
if (ret)
{
row.ItemArray = frm.Row.ItemArray;
string DegiskenId;
DegiskenId = row[0].ToString();
#region Kaydet guncelle hata kontrolu
try
{
#region Guncelle
if (KayitSekli == "GUNCELLE")
{
string gsorgu = "UPDATE OrnekTbl SET ProjectName=#ProjectName,UnitPrice=#UnitPrice,TotalPrice=#TotalPrice WHERE ProjectName='" + DegiskenId + "'";
objSqlDataAdapter.UpdateCommand = new SqlCommand(gsorgu, objSqlConnection);
objSqlDataAdapter.UpdateCommand.Parameters.Add("#ProjectName", SqlDbType.VarChar).Value = row[0].ToString();
objSqlDataAdapter.UpdateCommand.Parameters.Add("#UnitPrice", SqlDbType.VarChar).Value = row[1].ToString();
objSqlDataAdapter.UpdateCommand.Parameters.Add("#TotalPrice", SqlDbType.VarChar).Value = row[2].ToString();
{
objSqlConnection.Open();
objSqlDataAdapter.UpdateCommand.ExecuteNonQuery();
}
objSqlConnection.Close();
}
#endregion
#region Kaydet
if (KayitSekli == "KAYDET")
{
string ksorgu = "INSERT INTO OrnekTBL (ProjectName,UnitPrice,TotalPrice) VALUES (#ProjectName,#UnitPrice,#TotalPrice)";
objSqlDataAdapter.InsertCommand = new SqlCommand(ksorgu, objSqlConnection);
objSqlDataAdapter.InsertCommand.Parameters.Add("#ProjectName", SqlDbType.VarChar).Value = row[0].ToString();
objSqlDataAdapter.InsertCommand.Parameters.Add("#UnitPrice", SqlDbType.VarChar).Value = row[1].ToString();
objSqlDataAdapter.InsertCommand.Parameters.Add("#TotalPrice", SqlDbType.VarChar).Value = row[2].ToString();
if (objSqlConnection.State == ConnectionState.Closed)
{
objSqlConnection.Open();
objSqlDataAdapter.InsertCommand.ExecuteNonQuery();
}
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
objSqlConnection.Close();
}
#endregion
row.EndEdit();
}
return ret;
}
#endregion
The error message seems pretty clear. Take a look at your parameters:
objSqlDataAdapter.UpdateCommand.Parameters.Add("#UnitPrice", SqlDbType.VarChar).Value = row[1].ToString();
objSqlDataAdapter.UpdateCommand.Parameters.Add("#TotalPrice", SqlDbType.VarChar).Value = row[2].ToString();
You're explicitly declaring them as SqlDbType.VarChar. The field names, however, suggest that they are numeric values. (Money? Decimal?) The parameters need to match the data types of the columns. Perhaps something like this:
decimal unitPrice = 0;
if (!decimal.TryParse(row[1].ToString(), out unitPrice))
{
// TODO: Handle the error if it's not a valid decimal
}
objSqlDataAdapter.UpdateCommand.Parameters.Add("#UnitPrice", SqlDbType.Decimal).Value = unitPrice;
Related
My create statement could not work suddenly and it goes straight to an error message (Account cannot be created). I am not sure where I went wrong as I did not make any modification to it at all. In total, I have encountered this problem THRICE and my only solution is to make a new project for it to work again with the same exact codes. Any suggestions to ensure no such thing happen again in the future? Thank you in advance! Here are my codes in the controller:
[HttpPost]
public IActionResult CreateUser(Users usr)
{
if (!ModelState.IsValid)
{
ViewData["Message"] = "Invalid Input";
ViewData["MsgType"] = "warning";
return View("CreateUser");
}
else
{
string insert = #"INSERT INTO WBUsers(UserId, UserPw,FullName, Email, UserRole, Dob, ContactNo, usr.Billing_Address)
VALUES('{0}', HASHBYTES('SHA1', '{1}'), '{2}', '{3}', '{4}', '{5}', {6}, '{7}')";
if (DBUtl.ExecSQL(insert, usr.UserId, usr.UserPw, usr.FullName, usr.Email, usr.UserRole, usr.Dob, usr.ContactNo, usr.Billing_Address) == 1)
{
string template = #"Hi {0},<br/><br/>
Welcome to WorldBay!
Your userid is <b>{1}</b> and password is <b>{2}</b>. Please change your password upon login.
<br/><br/>Adminstrator";
string title = "Account Sign Up";
string message = String.Format(template, usr.FullName, usr.UserId, usr.UserPw);
string result = "";
bool outcome = false;
outcome = EmailUtl.SendEmail(usr.Email, title, message, out result);
if (outcome)
{
ViewData["Message"] = "Account has been created";
ViewData["MsgType"] = "success";
}
else
{
ViewData["Message"] = result;
ViewData["MsgType"] = "warning";
}
}
else
{
ViewData["Message"] = "Account cannot be created";
ViewData["MsgType"] = "danger";
}
return View("CreateUser");
}
}
DBUtil code consists of:
public static int ExecSQL(string sql, params object[] list)
{
List<String> escParams = new List<String>();
foreach (object o in list)
{
if (o == null)
escParams.Add("");
else
escParams.Add(EscQuote(o.ToString()));
}
DB_SQL = String.Format(sql, escParams.ToArray());
int rowsAffected = 0;
using (SqlConnection dbConn = new SqlConnection(DB_CONNECTION))
using (SqlCommand dbCmd = dbConn.CreateCommand())
{
try
{
dbConn.Open();
dbCmd.CommandText = DB_SQL;
rowsAffected = dbCmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
DB_Message = ex.Message;
rowsAffected = -1;
}
}
return rowsAffected;
}
I have used script task in ssis package to generate loads of excel files automatically every month.
Untill now script task worked fine but this month failed and when I did debug error showing at below
results = re.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
How can I fix this?
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
// TODO: Add your code here
string ssrsReport;
string destination;
string monthName;
string yyyy;
string currentReportName;
string currentReportShortName;
string password;
string filetype;
string version;
yyyy = (string)Dts.Variables["varYear"].Value;
monthName = (string)Dts.Variables["varMonthName"].Value;
filetype = (string)Dts.Variables["varFileType"].Value;
version = (string)Dts.Variables["varVersion"].Value;
// The SQL Task already ensures that these following five values are not null:
currentReportShortName = (string)Dts.Variables["varRSParameter"].Value;
currentReportName = (string)Dts.Variables["varRSReportName"].Value;
password = (string)Dts.Variables["varRSPassword"].Value;
destination = (string)Dts.Variables["varDestinationPath"].Value + "\\" + "Data - " + currentReportName + " " + monthName + " - " + yyyy + "." + filetype;
ssrsReport = (string)Dts.Variables["varSSRSReport"].Value;
try
{
CreateFolder((string)Dts.Variables["varDestinationPath"].Value);
RenderReport(destination, ssrsReport, currentReportShortName, password, filetype, version);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch
{
Dts.TaskResult = (int)ScriptResults.Failure;
throw;
}
}
private void RenderReport(string destinationFile, string ssrsReport, string agent, string password, string filetype, string version)
{
string historyID = null;
string deviceInfo = null;
string format = null;
if (filetype == "xls")
{
format = "Excel"; //Can be XML, NULL, CSV, IMAGE, PDF, HTML4.0, HTML3.2, MHTML, EXCEL, and HTMLOWC
}
else if (filetype == "pdf")
{
format = "PDF";
}
Byte[] results;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
ReportExecutionService.Warning[] warnings = null;
string[] streamIDs = null;
ReportExecutionService.ReportExecutionService re = new ReportExecutionService.ReportExecutionService();
re.Credentials = System.Net.CredentialCache.DefaultCredentials;
re.Timeout = 600000;
try
{
ReportExecutionService.ExecutionInfo ei = re.LoadReport(ssrsReport, historyID);
// If we need to generate a parametised report then do that here:
// check if multiple agent parameters are being passed for this report
ReportExecutionService.ParameterValue[] rptParameters = new ReportExecutionService.ParameterValue[4];
rptParameters[0] = new ReportExecutionService.ParameterValue();
rptParameters[0].Name = "DataName";
rptParameters[0].Value = agent;
rptParameters[1] = new ReportExecutionService.ParameterValue();
rptParameters[1].Name = "Year";
rptParameters[1].Value = (string)Dts.Variables["varYear"].Value;
rptParameters[2] = new ReportExecutionService.ParameterValue();
rptParameters[2].Name = "Month";
rptParameters[2].Value = (string)Dts.Variables["varMonth"].Value;
rptParameters[3] = new ReportExecutionService.ParameterValue();
rptParameters[3].Name = "version";
rptParameters[3].Value = (string)Dts.Variables["varVersion"].Value;
re.SetExecutionParameters(rptParameters, "en-GB");
results = re.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
FileStream stream = File.Create(destinationFile, results.Length);
stream.Write(results, 0, results.Length);
stream.Close();
if (password != "NONE" && password.Length > 0)
{
PasswordProtectExcel(destinationFile, password);
}
}
catch (Exception e)
{
throw new Exception("Error caught within RenderReport method: ", e);
}
}
private void CreateFolder(string path)
{
try
{
bool exists = Directory.Exists((string)Dts.Variables["varDestinationPath"].Value);
if (!exists)
System.IO.Directory.CreateDirectory((string)Dts.Variables["varDestinationPath"].Value);
}
catch (Exception e)
{
throw new Exception("Error caught within CreateFolder method: ", e);
}
}
// Code adapted from http://www.sqlservercentral.com/articles/Integration+Services+(SSIS)/71222/
private void PasswordProtectExcel(string excelSourceFile, string password)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
try
{
//open the Excel application
excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelWorkbook = excelApp.Workbooks.Open(excelSourceFile, 0, false, Type.Missing, Type.Missing, Type.Missing, true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", false, false,
0, false, false, false);
//Save the file with the "excelSourceFile" name
excelApp.DisplayAlerts = false;
excelWorkbook.SaveAs(excelSourceFile, Type.Missing, password, //password is used in the SaveAs function
Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, true, Type.Missing,
Type.Missing, Type.Missing);
}
catch (Exception e)
{
throw new Exception("Error caught within PasswordProtectExcel method: ", e);
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
//Close the workbook
excelWorkbook.Close(true, excelSourceFile, false);
Marshal.FinalReleaseComObject(excelWorkbook);
excelWorkbook = null;
//Quit the application
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
}
}
}
i am creating a one withdarw window my database connection code is right and its display result on same form correctly i want to show the result on next form .
i am implemeted code for that .give me error " inaccessible due to protection level " i search many code but not got any solutions .
this give on this line error " rece.Default.lblbal.Text = balance;".
this my code :
namespace ATMManagementSystem
{
public partial class cust_cash_with_sav : Form
{
public cust_cash_with_sav()
{
InitializeComponent();
}
#region Default Instance
public static cust_cash_with_sav defaultInstance;
/// <summary>
/// Added by the VB.Net to C# Converter to support default instance behavour in C#
/// </summary>
public static cust_cash_with_sav Default
{
get
{
if (defaultInstance == null)
{
defaultInstance = new cust_cash_with_sav();
defaultInstance.FormClosed += new
FormClosedEventHandler(defaultInstance_FormClosed);
}
return defaultInstance;
}
}
static void defaultInstance_FormClosed(object sender,
FormClosedEventArgs e)
{
defaultInstance = null;
}
#endregion
SqlConnection con = new SqlConnection("Data Source=VAIO;Initial
Catalog=ATM;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataSet ds;
int num1;
int num2;
int total1;
string balance;
public void button1_Click(object sender, EventArgs e)
{
string sql = default(string);
DataTable Log_in = new DataTable();
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM user_transaction
where pin_number = " + textBox2.Text + "", con);
cmd.Connection = con;
//da.SelectCommand = cmd;
da = new SqlDataAdapter(cmd);
da.Fill(Log_in);
if (Log_in.Rows.Count > 0)
{
balance = (string)(Log_in.Rows[0]["Total"].ToString());
num1 = int.Parse(balance);
num2 = int.Parse(textBox1.Text);
if (num2 > 25000)
{
MessageBox.Show("You can Only Withdraw Php 25,000");
}
else if (num2 < 200)
{
MessageBox.Show(" Mininum withdrawal is 200");
}
else if (num1 < num2)
{
MessageBox.Show(" Insuffiecient balance");
}
else
{
total1 = num1 - num2;
rece.Default.Show();
rece.Default.lblbal.Text = balance;
rece.Default.lbldep.Hide();
rece.Default.lblwith.Text = num2.ToString();
rece.Default.lblnewbal.Text = total1.ToString();
rece.Default.lblbal.Show();
rece.Default.lbldep.Hide();
rece.Default.lblwith.Show();
rece.Default.lblnewbal.Show();
//MsgBox("success")
rece.Default.lblname.Text =
Mainmenu.Default.lblname.Text;
label2.Text = total1.ToString();
//this.Hide();
}
}
else
{
}
}
catch (Exception)
{
// MessageBox.Show(" Pls. Enter Ammount!");
//MsgBox(ex.Message)
}
textBox1.Text = "";
}
}
}
You can try this
//In Form1's
using(rece form2 = new rece())
{
form2.TheValue = someControlOnForm1.Text;
}
And...
//In rece form
//Create a public property to serve the value
public string TheValue
{
set { lblbal.Text = value;}
}
I have two functions that have queries that return shipping areas. One returns a pilots certified areas and the other returns areas between point A and B. I want to compare them and select the check boxes of the matching areas. Here is what I have.
private void getAreaText(string PilotID)
{
SqlConnection sqlCN;
SqlCommand sqlCOM;
SqlDataReader sqlDR;
DateTime dato;
string strCOM = ConfigurationManager.AppSettings["database"];
sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
sqlCOM = new SqlCommand("select f_AreaText, f_DateOfIssue from v_GetAreaText where f_PilotID='" + PilotID + "'", sqlCN);
sqlDR = sqlCOM.ExecuteReader();
CheckBoxList1.Items.Clear();
while (sqlDR.Read())
{
dato = sqlDR.GetDateTime(1);
dato = dato.AddYears(1);
if (DateTime.Now < dato)
CheckBoxList1.Items.Add(sqlDR.GetString(0));
if (CheckBoxList1.Items.Contains(findAreas(Session["PilotID"].ToString)))
{
CheckBoxList1.Items[i].Selected = true;
}
}
sqlDR.Close();
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return;
}
protected void findAreas(string PilotID)
{
SqlConnection sqlCN;
SqlCommand sqlCOM;
SqlDataReader sqlDR;
string strCOM = ConfigurationManager.AppSettings["database"];
sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
sqlCOM = new SqlCommand("select DISTINCT f_AreaText from v_FindAreas where f_PilotID='" + PilotID + "'and f_SailedFrom='" + getLMFromList(FromList) + "'and f_SailedTo='" + getLMFromList(ToList) + "'", sqlCN);
sqlDR = sqlCOM.ExecuteReader();
CheckBoxList1.Items.Clear();
while (sqlDR.Read())
{
CheckBoxList1.Items.Add(sqlDR.GetString(0));
}
sqlDR.Close();
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return;
}
Your code is quite confusing so here is an attempt to organize it a little and make it work at the same time. There's a lot more you could do to improve it but since I'm coding in the dark, I haven't changed it too much. The main thing I've changed is to use SQL parameters instead of concatenating values into a literal command.
private void getAreaText(string PilotID)
{
var strCOM = ConfigurationManager.AppSettings["database"];
var sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
var sqlCOM = new SqlCommand("select f_AreaText, f_DateOfIssue from v_GetAreaText where f_PilotID=#p1", sqlCN);
sqlCOM.Parameters.AddWithValue("#p1", PilotID);
var sqlDR = sqlCOM.ExecuteReader();
CheckBoxList1.Items.Clear();
while (sqlDR.Read())
{
var dato = sqlDR.GetDateTime(1);
dato = dato.AddYears(1);
if (DateTime.Now < dato)
{
var AreaText = sqlDR.GetString(0);
CheckBoxList1.Items.Add(AreaText);
if (findAreas(PilotID, AreaText))
// Do you want Selected here or Checked ?
CheckBoxList1.Items[CheckBoxList1.Count-1].Selected = true;
}
}
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlDR.Close();
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return;
}
protected bool findAreas(string PilotID, string AreaText)
{
var strCOM = ConfigurationManager.AppSettings["database"];
var sqlCN = new SqlConnection(strCOM);
try
{
sqlCN.Open();
sqlCOM = new SqlCommand("select DISTINCT f_AreaText from v_FindAreas where f_PilotID=#p1 and f_SailedFrom=#p2 and f_SailedTo=#p3 and f_AreaText=#p4", sqlCN);
sqlCOM.Parameters.AddWithValue("#p1", PilotID);
sqlCOM.Parameters.AddWithValue("#p2", getLMFromList(FromList));
sqlCOM.Parameters.AddWithValue("#p3", getLMFromList(ToList));
sqlCOM.Parameters.AddWithValue("#p4", AreaText);
var sqlDR = sqlCOM.ExecuteReader();
if (sqlDR.HasRows)
return true;
}
catch (DataException ex)
{
Response.Write(ex.ToString());
}
finally
{
sqlDR.Close();
sqlCN.Close();
sqlDR = null;
sqlCOM = null;
sqlCN = null;
}
return false;
}
I have problem when trying to fetch the data from database and display in database. I get from user input and store as a search variable. This is how I set up my table:
//I get the user input to perform search
#FXML
public void searchResident(ActionEvent event){
String search=getTb_search().getText();
if(search.equals("")){
Dialogs.showErrorDialog(null, "Please enter something", "Blank fields detected", "");
}else{
setUpSearchTable(search);
}
}
//How I set up my table
public void setUpSearchTable(String search) {
TableColumn rmNameCol = new TableColumn("Name");
rmNameCol.setVisible(true);
rmNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<SearchNeedyResidentController, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<SearchNeedyResidentController, String> p) {
return p.getValue().searchNameProperty();
}
});
TableColumn rmNricCol = new TableColumn("NRIC");
rmNricCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_nric"));
rmNricCol.setMinWidth(150);
TableColumn rmPhNoCol = new TableColumn("Phone Number");
rmPhNoCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController,String>("search_phNo"));
rmPhNoCol.setMinWidth(350);
TableColumn rmIncomeCol = new TableColumn("Income($)");
rmIncomeCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_income"));
rmIncomeCol.setMinWidth(100);
ResidentManagement.entity.NeedyResidentEntity searchValue= new ResidentManagement.entity.NeedyResidentEntity();
//viewProduct.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table_search.setEditable(false);
table_search.getColumns().addAll(rmNricCol, rmNameCol, rmIncomeCol, rmPhNoCol);
table_search.getItems().setAll(searchValue.searchResident(search));
}
}
//How I populate the table data
public List<SearchNeedyResidentController> searchResident(String search){
List ll = new LinkedList();
try {
DBController db = new DBController();
db.getConnection();
String sql = "SELECT * FROM rm_needyresident WHERE name LIKE '" + search + "%'";
ResultSet rs = null;
// Call readRequest to get the result
rs = db.readRequest(sql);
while (rs.next()) {
String nric=rs.getString("nric");
String name = rs.getString("name");
double income = rs.getDouble("familyIncome");
String incomeStr = new DecimalFormat("##.00").format(income);
String phNo = rs.getString("phNo");
SearchNeedyResidentController row = new SearchNeedyResidentController();
row.setSearchNric(nric);
row.setSearchName(name);
row.setSearchIncome(incomeStr);
row.setSearchPhNo(phNo);
ll.add(row);
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Error SQL!!!");
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
return ll;
}
}
When search button is on click, the table column is displayed. However, it's just show a blank table even though there's matching result. I debug already and I think the error is at the retrieving data in the searchResident method. It's not retriving the data from database. Anybody know what's wrong?
Thanks in advance.
try dis one...
#FXML private void SearchButton()
{
Connection c ;
datamem = FXCollections.observableArrayList();
try
{
c = Dao.getCon();
String SQL =SELECT * FROM `Member`;
ResultSet rs = c.createStatement().executeQuery(SQL);
if(table.getColumns().isEmpty())
{
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++)
{
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
table.getColumns().addAll(col);
}//for
}//if
while(rs.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++)
{
row.add(rs.getString(i));
}// for
datamem.add(row);
}//while
table.setItems(datamem);
}//try
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Problem in Search Button "+e);
}
}//else
}//else
} //search method