how can i solve the system.invalidcastexception - c#

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlcon1 = new SqlConnection(#"Data Source=PRATHISTA;Initial Catalog=CRMT;Integrated Security=True");
sqlcon1.Open();
SqlCommand cmd1 = new SqlCommand("select * from Requirement", sqlcon1);
try
{
SqlDataReader sda1 = cmd1.ExecuteReader();
while (sda1.Read())
{
string sId = sda1.GetString("Requirement_Id");
// i get the error here;
}
sda1.Close();
sqlcon1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex);
}
}

As your id column isn't a string, the database doesn't return a string - you can only use the GetString method for string columns. You now have two options:
Using GetInt32
Directly getting the data from the reader
The first option is done like that:
var sId = sda1.GetInt32(index);
Remember however that the index here can't be of type string and must be an integer.
The second option is better (in my opinion) in that case:
var sId = (int)sda1["Requirement_Id"];
You can (of course) still use a string:
var sId = sda1["Requirement_Id"].ToString();

Related

Retrieve single user data from oracle database into visual studio C# application

I am using forms in visual studio to create an application and then retrieve data from Oracle database. My all parts are working except getting data for the single user. Here is form.cs section for that part
private void getCustomerStringToolStripMenuItem_Click(object sender, EventArgs
e)
{
Getcuststring g = new Getcuststring();
g.Show();
}
This is my partial class named getcuststring.cs
namespace Assignment
{
public partial class Getcuststring : Form
{
public Getcuststring()
{
InitializeComponent();
}
private void Getcuststring_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Getting();
}
public void Getting()
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =" + "(ADDRESS = (PROTOCOL = TCP)" +
"(HOST = *******)(PORT = 1521))" + "(CONNECT_DATA =" + "(SID = dms)));"
+ "User Id= *****;Password= ******;";
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "GET_CUST_STRING_FROM_DB";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("pcustid", OracleDbType.Long).Value = textBox1.Text;
cmd.Parameters.Add("return_value", OracleDbType.Varchar2).Direction = ParameterDirection.ReturnValue;
try
{
cmd.ExecuteNonQuery();
// string result = string.Empty;
var result = cmd.Parameters["result_value"].Value.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
my all other functions are working but when executing this in visual studio it every time give exception out saying no data is found whereas that customer id is present in the Oracle database but it somehow not showing the result but instead raising the exception.
So can u tell me where I am wrong, why he's providing me with an exception saying no data found whereas that data actually exist.
This is the function
CREATE OR REPLACE FUNCTION GET_CUST_STRING_FROM_DB(pcustid NUMBER) RETURN
VARCHAR2 AS
vcustid NUMBER;
vcustname VARCHAR2(255);
vcustsales NUMBER;
vcuststatus VARCHAR2(255);
BEGIN
SELECT CUSTID,CUSTNAME,SALES_YTD,STATUS INTO
vcustid,vcustname,vcustsales,vcuststatus
FROM CUSTOMER
WHERE CUSTID = pcustid;
RETURN 'CustID: ' || vcustid || ' Name: ' || vcustname || ' Status: ' ||
vcuststatus || ' SalesYTD: ' || vcustsales;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20021,'Customer ID not found');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20000,SQLERRM);
END;
I think it is simple typo, line
var result = cmd.Parameters["result_value"].Value.ToString();
should be:
var result = cmd.Parameters["return_value"].Value.ToString();
I built similiar case, and got System.IndexOutOfRangeException when I run it. Correcting typo solved problem. Whole code which worked for me:
OracleConnection CONNECTION
= new OracleConnection("Data Source=XX;User Id=XX;Password=XX;");
CONNECTION.Open();
OracleCommand cmd = new OracleCommand() { Connection = CONNECTION };
cmd.CommandText = "GET_CUST_STRING_FROM_DB";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("pcustid", OracleType.Double).Value = textBox1.Text;
cmd.Parameters.Add("return_value", OracleType.VarChar, 500).Direction
= System.Data.ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
var result = cmd.Parameters["return_value"].Value.ToString();
Console.WriteLine(result);
CONNECTION.Close();

update statement error in image

private void btnupdate_Click(object sender, EventArgs e)
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
try
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Update not possible");
}
else
{
cnn.Open();
cmd3.CommandText = "update Slab set indi = #img1 where s_flatno = #s_flatno and s_name = #s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
cnn.Close();
}
}
In this code, I'm updating image in the position indi and I'm setting a new img1 in byte. While press update I'm getting an error
Must declare scalar variable #img1
You have named your variable #img1 in the SQL Statement, but #indi when you declared the variable.
Please note that best practice when handling DBConnection is as a local variable inside a using statement, and you better use one of the overloads of Add when adding parameters to a command instead of AddWithValue. For more information, read Can we stop using AddWithValue() already?
Here is an improved version of your code:
private void btnupdate_Click(object sender, EventArgs e)
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Updation not possible");
}
else
{
try
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
var sql = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
// I'm assuming SQL Server based on the error message
using(var cnn = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#indi", SqlDbType.VarBinary).Value = img1;
cmd.Parameters.Add("#s_flatno", SqlDbType.VarChar).Value = txtfno.Text;
cmd.Parameters.Add("#s_name", SqlDbType.VarChar).Value = txtslab.Text;
}
cnn.Open();
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
There is a small issue with you code. You have not passed #img1 parameter. You are sending it as #indi. Either Change #img1 to #indi in sql query string or change #indi to #img1 in add parameter statement:
cnn.Open();
cmd3.CommandText = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();

c# mysql unable to output query to a textbox

here is my code:
private void searchInDatabase()
{
MySqlConnection c = new MySqlConnection("datasource=localhost; username=root; password=123456; port=3306");
MySqlCommand mcd;
MySqlDataReader mdr;
String query;
try
{
c.Open();
query = "SELECT * FROM test.classmates WHERE first_name ='"+searchName.Text+"'";
mcd = new MySqlCommand(query, c);
mdr = mcd.ExecuteReader();
if(mdr.Read())
{
firstName.Text = mdr.GetString("first_name");
middleName.Text = mdr.GetString("middle_name");
lastName.Text = mdr.GetString("last_name");
age.Text = mdr.GetString("age");
}
else
{
MessageBox.Show("Result Not Found");
}
}
catch(Exception error)
{
MessageBox.Show("Error: "+error.Message);
}
finally
{
c.Close();
}
}
I would like to ask for a help if I have missed on anything or I am doing it wrong. If you have free time, I will much appreciate it if you will comment the perfect way to do I implement this problem: I want to get data from MySQL then put it in a textbox.
According to MSDN you need to pass the column number as parameter
public override string GetString(int i)
So try to pass the column number (starts from 0) of your column name. Assuming the first_name is the first column of your table then
firstName.Text = mdr.GetString(0);
UPDATE
Try to use MySqlConnectionStringBuilder
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "serverip/localhost";
conn_string.UserID = "my_user";
conn_string.Password = "password";
conn_string.Database = "my_db";
MySqlConnection conn = new MySqlConnection(conn_string.ToString();
First of all look at this sample of connection string and change your connection string:
'Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPasswor;'
If connection is OK send erorr message or full exception.

Getting data from MS Access database and display it in a listbox

How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.
private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Sisc-stronghold\mis!\wilbert.beltran\DataBase\DataStructure.accdb"))
using(OleDbCommand cmd = new OleDbCommand(" SELECT * from TableAcct", conn))
{
conn.Open();
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
listBox1.Text = Reader.GetString("FirstName");
}
}
the errors are here:
1. Error 1 The best overloaded method match for'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments.
2. Error 2 Argument '1': cannot convert from 'string' to 'int'
try this one,
List<String> firstName = new List<String>();
List<String> lastName = new List<String>();
private void loadButton_Click(object sender, EventArgs e)
{
cn.Open();
OleDbDataReader reader = null;
cmd = new OleDbCommand("select* from Records", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
firstName.Add(reader["FirstName"].ToString());
lastName.Add(reader["LastName"].ToString());
}
cn.Close();
}
then in your search button, insert this,
private void searchButton_Click(object sender, EventArgs e)
{
clearSearchResult();
try
{
int totalItems = FirstName.Count;
int count = 0;
while (count < totalItems)
{
if (textBox6.Text == FirstName[count].ToString())
{
listBox1.Items.Add(FirstName[count].ToString());
count = 100;
}
else
{
count++;
}
It's good to use when you want to show the information of the "FirstName" in the listBox1_SelectedIndexChanged if you want. here's an example,
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int totalItems = lastName.Count;
int count = 0;
while (count < totalItems)
{
if ((listBox1.SelectedItem.ToString()) == firstName[count].ToString()))
{
textBox1.Text = firstName[count].ToString();
textBox2.Text = lastName[count].ToString();
count = 100;
}
else
{
count++;
}
}
hope this helps,
change
listBox1.Text = Reader.GetString("FirstName");
to
listBox1.Text = Reader.GetString(0); // zero base ordinal of column
GetString() takes an int as the parameter and not a string. Meaning that you must use the index of the column.
In your specific circumstance as "FirstName" is the second column the index would be 1:
listBox1.Text = Reader.GetString(1);
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
Thy using a While loop
while(reader.Read())
{
listbox1.Items.Add(reader["FirstName"]);
}
This moves through all the rows you selected. reader.Read() returns false if there are no more rows.
Also: if you Want to retrive valmue from a column I suggest you do it with the index ón the reader instance. Like my example.
var value = reader["ColumnName"];
This increases readability comparing to
var value = reader.GetString(0);
UPDATE
If you want to only display the fist value - I suggest you use cmd.ExecuteScalar() and the adapt you sql to only return the value you need:
using(OleDbCommand cmd = new OleDbCommand("SELECT firstname from TableAcct", conn))
{
conn.Open();
var firstName = cmd.ExecuteScalar();
}
Be aware the this will give you the first "FirstName" in the table. And since there is no "order by firstname" or "where someKey = 1" - this might not rturn that you expected.
If you want to create MS Access data base and to access it, and to display data in some component, like here i will show you.how to connect with MS Access Data Base and display data from data base in Label.
First of all create any Access data base like here "PirFahimDataBase".
Now in your Visual Studio go to the menu and do this
Click Data
Add New Data Base
Click Next
Click New Connection
Now change the Data Source by clicking Change and select Microsoft Access data base files
Click Browse for selecting your created data base
Now in Button ClickEvent paste these code which will get data from data base and will show it in the label
using System.Windows.Forms; //these two lines should be written before namespace at top of the program
using System.Data.OleDb;
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\PirFahimDataBase.accdb";
try
{
conn.Open();
MessageBox.Show("connected successfuly");
OleDbDataReader reader = null; // This is OleDb Reader
OleDbCommand cmd = new OleDbCommand("select TicketNo from Table1 where Sellprice='6000' ", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label1.Text= reader["TicketNo"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}//end of button click event
Your error is in this line:
listBox1.Text = Reader.GetString("FirstName");
You must pass a number in the GetString() function.
DataColumn[] PrimaryKeyColumn = new DataColumn[1]; //Define Primary coloumn
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
ReadAndUpdateExcel.ReadExcel(strPath, sheetName, out dataSet);
dataSet.Tables.Add(dataTable);
PrimaryKeyColumn[0] = dataSet.Tables[0].Columns[0];
dataSet.Tables[0].PrimaryKey = PrimaryKeyColumn;
string num = dataSet.Tables[0].Rows[dataSet.Tables[0].Rows.IndexOf(dataSet.Tables[0].Rows.Find(strTCName))]["ACNO"].ToString();
//string country

No Value Give For One Or More Parameters?

i have a buttonfield in a gridview, when i press that button it takes the id value from the first column, i use that id in a select statement, to get data from the table, but i get this error "No Value Give For One Or More Parameters"
protected void grdData_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdData.SelectedRow;
string id = row.Cells[1].Text;
try
{
conn.ConnectionString = conn_string;
conn.Open();
mySQLCommand.Connection = conn;
mySQLCommand.CommandText = "Select [Movie_Description],[Movie_Image] from Movie_tbl where Movie_ID = #Movie_ID";
mySQLCommand.Parameters.Add("#Movie_ID", OleDbType.VarChar).Value = id;
myDataReader = mySQLCommand.ExecuteReader();
if (myDataReader.Read())
{
txtDescription.Text = myDataReader["Movie_Description"].ToString();
}
else
{
txtDescription.Text = "No Such Movie";
}
}
catch (Exception ex)
{
throw ex ;
}
}
I haven't worked with mySQL much, but I'm pretty sure you don't want an OleDbType.VarChar parameter. I haven't seen that used outside of MS Access. Try:
mySQLCommand.Parameters.AddWithValue("#Movie_ID", id);
if that fails, maybe try
mySQLCommand.Parameters.Add(new MySqlParameter("#Movie_ID", id));
mySQLCommand is of type MySqlCommand in your code, right?

Categories