Failed to convert parameter value from a String to a Int32 c# - string

I have two DROP DOWN LISTs :one for PROVINCE and one for CITY which are connected to a DB.
I want to be able to select a PROVINCE from the first drop down list and be able to see the
CITIES of that special PROVINCE in the second drop down list.
But I receive the error "Failed to convert parameter value from a String to a Int32." on line "DataSet ds1 = new DataSet();".
My DB:
--------
_Province
Prv_Id --- int (P.key)
Prv_Name --- nvarchar
--------------
_City
Cty_Id --- int (P.key)
Cty_Name --- nvarchar
Cty_Prv_Id --- int (F.key)
----------------------------
----------------------------
My ST.Procedures:
-----------------------
ALTER PROCEDURE [dbo].[_City_selectItems] (#vari int)
AS
BEGIN
SELECT * FROM _City WHERE (Cty_Prv_Id=#vari)
END
--------------------------------------------------
ALTER PROCEDURE [dbo].[_Province_selectAll]
AS
BEGIN
SELECT * FROM _Province
END
--------------------------------------------------
MY CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication3_DrpDwnListAndSQL
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
func1();
func2();
//func3();
}
}
protected void DrpDwnProvince_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text =DrpDwnProvince.SelectedValue;
//string a = DrpDwnProvince.SelectedValue;
}
//First function for Province DrpDwnList
private void func1()
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DrpBoxDB;Data Source=ARASH-PC");
SqlDataAdapter com = new SqlDataAdapter("_Province_selectAll", con);
com.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
if (com != null)
{ com.Fill(ds); }
DrpDwnProvince.DataSource = ds;
DrpDwnProvince.DataTextField = "Prv_Name";
DrpDwnProvince.DataValueField = "Prv_Id";
DrpDwnProvince.DataBind();
}
//Second function for City DrpDwnList
private void func2()
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DrpBoxDB;Data Source=ARASH-PC");
SqlDataAdapter com1 = new SqlDataAdapter("_City_selectItems", con);
com1.SelectCommand.Parameters.Add("#vari",SqlDbType.Int).Value=Label1.Text;
com1.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds1 = new DataSet();
if (com1 != null)
{ com1.Fill(ds1); }
DrpDwnCity.DataSource = ds1;
DrpDwnCity.DataTextField = "Cty_Name";
DrpDwnCity.DataValueField = "Cty_Id";
DrpDwnCity.DataBind();
}
//Third function for District DrpDwnList
// private void func3()
// {
// }
}
}

Related

dependent spinner with sqlite isn't working

`I'm trying to create a dependent spinner with data from sqlite on android studio. But the spinners isn't showing any content as intended. The Prefix is suppose to narrow down the selection for the Lotno and finally display the Plantation_name based on database SmartSawit.db. pls help :> (its been days)
Spinner spinnerPrefix, spinnerLotno, spinnerPlantation_name;
Context context;
database Database;
String prefixValue, lotnoValue, nameValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daftar_pokok);
spinnerPrefix = findViewById(R.id.spinnerPrefix);
spinnerLotno = findViewById(R.id.spinnerLotno);
spinnerPlantation_name = findViewById(R.id.spinnerPlantation_name);
context = this;
Database = new database(this, "SmartSawit.db", 1);
try {
Database.CheckDB();
fillSpinner(context,spinnerPrefix, "registered_plantation", "prefix", "");
spinnerPrefix.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
prefixValue = parent.getItemAtPosition(position).toString();
fillSpinner(context,spinnerLotno,"registered_plantation","lotno","where prefix = '"+prefixValue+"'");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerLotno.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
lotnoValue = parent.getItemAtPosition(position).toString();
fillSpinner(context,spinnerPlantation_name,"registered_plantation","plantation_name","where prefix = '"+prefixValue+"' and lotno ='"+lotnoValue+"'");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}catch(Exception e){
e.printStackTrace();
}
}
#SuppressLint("Range")
private void fillSpinner (Context context, Spinner mSpinner,String table, String column, String where) {
SQLiteDatabase db = Database.OpenDatabase("registered_plantation.db");
ArrayList<String> mArray = new ArrayList<>();
Cursor cursor = db.rawQuery("Select distinct "+column+" from "+table+""+where, null);
while (cursor.moveToNext()){
mArray.add(cursor.getString(cursor.getColumnIndex(column)));
}
cursor.close();
db.close();
ArrayAdapter mAdapter = new ArrayAdapter(context, android.R.layout.simple_spinner_item,mArray);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(mAdapter);
}
}
my databasehelper code:
private Context context;
private static final String DATABASE_NAME = "SmartSawit.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "registered_plantation";
//private static final String COLUMN_NO = "_no";
private static final String COLUMN_NAME = "plantation_name";
private static final String COLUMN_PREFIX = "prefix";
private static final String COLUMN_LOT_NUMBER = "lotno";
String DbPath;
Context mcontext;
String DbName;
public database(Context context, String name, int version) {
super(context, DATABASE_NAME, null, version);
this.context = context;
this.mcontext = context;
this.DbName = DATABASE_NAME;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
this.DbPath = context.getFilesDir() + "/database/";
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_NAME + " TEXT PRIMARY KEY, " +
COLUMN_PREFIX + " TEXT, " +
COLUMN_LOT_NUMBER + " INTEGER);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void CheckDB(){
SQLiteDatabase checkDB = null;
String filePath = DbPath + DbName;
File file = new File(filePath);
if(file.isFile() && file.exists()){
Toast.makeText(mcontext, "already exist", Toast.LENGTH_SHORT).show();
} else {
CopyDatabase();
}
}
private void CopyDatabase(){
try {
InputStream ios = mcontext.getAssets().open(DbName);
File directory = new File(DbPath);
if(!directory.exists()){
directory.mkdirs();
}
OutputStream os = new FileOutputStream(DbPath + DbName);
byte[] buffer = new byte[1024];
int len;
while((len = ios.read(buffer)) >0) {
os.write(buffer,0, len);
}
os.flush();
ios.close();
os.close();
Log.d("CopyDb", "Databse Copied");
} catch (Exception e) {
e.printStackTrace();
}
}
void addLadang (String prefix, String namaLadang, int lotNo){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PREFIX, prefix );
cv.put(COLUMN_NAME, namaLadang );
cv.put(COLUMN_LOT_NUMBER, lotNo );
long result = db.insert(TABLE_NAME,null, cv);
if (result == -1){
Toast.makeText(context, "FAILED", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "SUCCESSFULLY SAVED", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
public SQLiteDatabase OpenDatabase(String dbName){
String filePath = DbPath + dbName;
return SQLiteDatabase.openDatabase(filePath,null,0);
}
}
You have a number of issues (not actually with the spinners).
First you are trying to open a non-existent database. That is you are using the the table name not the database name in the fillSpinner method by using:-
SQLiteDatabase db = Database.OpenDatabase("registered_plantation.db");
i.e. the database name is SmartSawit.db not registered_plantation.db.
The following fixes that issue (SEE EMBEDDED COMMENTS):-
SQLiteDatabase db = Database.OpenDatabase(/*"registered_plantation.db"<<<<<<<<<<< TABLE NAME NOt DATABASE NAME so USED >>>>>>>>>>*/ database.DATABASE_NAME /*after making it public */);
You then have issues with missing spaces in the WHERE clauses again in the fillSpinner method (fixed using, again see comments):-
Cursor cursor = db.rawQuery("Select distinct "+column+" from "+table+" "/*<<<<<<<<<< ADDED SPACE*/+where, null);
Applying the above fixes and using a layout that has the 3 spinners side by side and with different coloured backgrounds and with an excessive height. And with the following data in the database (in the assets folder name SmartSawit.db):-
Then when first run:-
Clicking on the first spinner
i.e. A and B, the 2 prefixes are selected accordingly
Clicking on B and
i.e. as expected
and so on.
Additional
If you checked the log with your original code, even though it doesn't crash you could have spotted the issue e.g. the log would have included:-
2023-02-07 11:13:59.641 24792-24792/a.a.so75365360javasqlitespinners D/CopyDb: Databse Copied
2023-02-07 11:13:59.642 24792-24792/a.a.so75365360javasqlitespinners E/SQLiteLog: (14) cannot open file at line 36667 of [c255889bd9]
2023-02-07 11:13:59.642 24792-24792/a.a.so75365360javasqlitespinners E/SQLiteLog: (14) os_unix.c:36667: (2) open(/data/user/0/a.a.so75365360javasqlitespinners/files/database/registered_plantation.db) -
2023-02-07 11:13:59.643 24792-24792/a.a.so75365360javasqlitespinners E/SQLiteDatabase: Failed to open database '/data/user/0/a.a.so75365360javasqlitespinners/files/database/registered_plantation.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14 SQLITE_CANTOPEN): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:211)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:195)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:503)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:204)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:196)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:880)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:865)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:766)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:714)
at a.a.so75365360javasqlitespinners.database.OpenDatabase(database.java:124)
at a.a.so75365360javasqlitespinners.MainActivity.fillSpinner(MainActivity.java:69)
at a.a.so75365360javasqlitespinners.MainActivity.onCreate(MainActivity.java:36)
So although the copy was successfully accomplished e.g. using Device Explorer you would something along the lines of:-
Thus it is easy to see that registered_plantation.db is not at the expected location but SmartSwait.db is.
In short. If using try/catch and things are not working as expected the Check the Log for what you expect to see in the log (e.g. looking for Database copied would have made it easy to see that things were not as expected as the error lines immediately follow that message).

sharepoint SPFarm.local.GetObject return null

I installed sharepoint foundation 2010 (in 'Standalone' type) on windows 2012 r2.
And I created a windows app project.
When Load , New Counter(farm) is success.
But, SPFarm.local.GetObject return null;
Does someone konw the reason,please help me.
source like this:
//-------source start-------
//Counter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace WinAppTest
{
class Counter : SPPersistedObject
{
public static String SettingName = "Counter";
public static String SettingGuid = "62648e50-8aee-42b2-b074-2f49ced85587";
[Persisted]
public String name;
[Persisted]
public String count;
public Counter()
{
}
public Counter(SPPersistedObject parent)
: base(SettingName, parent, new Guid(SettingGuid))
{
}
}
}
// Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
namespace WinAppTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Write_Click(object sender, EventArgs e)
{
SPFarm farm = SPFarm.Local;
//------- *conf is null*-----
Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
//------- *conf is null*-----
conf.Name = "pf1";
conf.count = "1";
conf.Update();
}
private void Form1_Load(object sender, EventArgs e)
{
SPFarm farm = SPFarm.Local;
Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
if (conf == null)
{
conf = new Counter(farm);
}
//------- *conf is null*-----
conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
//------- *conf is null*-----
String name = conf.name;
String count = conf.count;
}
}
}
Finally , I think the source has error in it.
modify like this, It's OK.
private void Write_Click(object sender, EventArgs e)
{
SPFarm farm = SPFarm.Local;
Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
if (conf == null)
{
conf = new Counter(farm);
}
conf.Name = "pf1";
conf.count = "1";
conf.Update();
}
private void Form1_Load(object sender, EventArgs e)
{
SPFarm farm = SPFarm.Local;
Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
String name = conf.name;
String count = conf.count;
}

I have many databound dropdowns on ASP.net. How to reuse the data binding code

I have a private function as below
private static void listSourceBind(SqlConnection sql,String table, String idColumn, String valueColumn, ref DropDownList dropDownList)
{
string sqlGetDataSource = "select "+ idColumn +", "+ valueColumn + " from "+ table;
SqlCommand selectDataSource = new SqlCommand(sqlGetDataSource, sql);
DataTable dataTable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(selectDataSource);
adapter.Fill(dataTable);
dropDownList.DataSource = table.ToString();
dropDownList.DataSourceID = null;
dropDownList.DataValueField = idColumn.ToString();
dropDownList.DataTextField = valueColumn.ToString();
dropDownList.DataBind();
}
that I am calling from Page_Load function as
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection(sourceDB);
listSourceBind(sql, "[SchemaName].[CInput]", "CID", "Desc", ref CInput);
}
However dropDownList.DataBind() method is throwing an excetion as below
An exception of type 'System.Web.HttpException' occurred in
System.Web.dll but was not handled in user code
Additional information: DataBinding: 'System.Char' does not contain a property with the name 'InputDesc'.
However if I code as below it works perfectly fine. Problem is that there is a lot of repetitive code needed for each dropdown list
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection(sourceDB);
string sqlGetDataSource = "select CID, Desc from [SchemaName].[CInput]";
SqlCommand selectDataSource = new SqlCommand(sqlGetDataSource, sql);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(selectDataSource);
adapter.Fill(table);
CInput.DataSource = table;
CInput.DataSourceID = null;
CInput.DataValueField = "CID";
CInput.DataTextField = "Desc";
CInput.DataBind();
}
Is there anyway I can write a function as I attempted above to avoid repetitive code

Edit Excel Column

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Text;
namespace SDM
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void browsefiles_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
display(openFileDialog1.FileName);
}
}
private void display(string text)
{
textBox1.Text = string.Format("{0}", openFileDialog1.FileName);
}
private void importFile_Click(object sender, EventArgs e)
{
string PathConn = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 12.0;\"");
OleDbConnection conn= new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text+ "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
if (textBox2.Text.Contains("Life Group"))
{
dt.Columns.Add("Agent Code", typeof(string));
}
else if (textBox2.Text.Contains("Life Individual"))
{
DataColumn col = dt.Columns[9].ToString();
String.Format("####-###");
Console.WriteLine(col);
myDataAdapter.Fill(dt);
}
I am trying to change the format of Column [9] from "1234567" to "1234-567". I just want to add a dash after the 4th number but am having trouble calling on that entire column to make the change. Can anybody lend any suggestions? It would be greatly appreciated.

System.Data.OleDb.OleDbException was unhandled; "Syntax error in INSERT INTO statement" in C# wh

using System.Data.OleDb;
namespace ConnectingToMS_Access1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
da = new OleDbDataAdapter("Select * from Record", "Provider=Microsoft.Ace.oledb.12.0;data source='D:\\mydb.accdb'");
ds = new DataSet();
da.Fill(ds);
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ds.Tables[0];
}
private void button2_Click(object sender, EventArgs e)
{
DataRow dr = ds.Tables[0].NewRow();
dr[0] = "abc";
dr[1] = "def";
dr[2] = "ghi";
dr[3] = "jkl";
ds.Tables[0].Rows.Add(dr);
}
private void button3_Click(object sender, EventArgs e)
{
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds.Tables[0]);
MessageBox.Show("Saved in Database");
}
}
}
You need to explicitly define the named columns in your query.
The problem is that you can't update columns based on column position. It might have been reasonable to expect that calling the Fill method would return both records and column-names, but it probably won't. After all, running that select query will return only data, not schema.

Resources