cannot convert from string to int - c#

i want to convert what i selected from the combobox so i can edit it or delete it, but the messege "cannot convert from string to int" keep showing
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
string Query = "select * from tbl_article where NameArticle='"+comboBoxArt.Text+"'";
SqlCommand cmd = new SqlCommand(Query, sqlCon);
SqlDataReader myReader;
try
{
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
txtName.Text = myReader.GetString("NameArticle");
txtPrice.Text = myReader.GetInt32("PriceArticle").ToString();
}
}
and also when i run it, the selected item changes to his id "IdArticle".
how can i fix this ??

Why not just do this?
txtName.Text = myReader["NameArticle"].ToString();
txtPrice.Text = myReader["PriceArticle"].ToString();
It should get whatever value from database whether its int or DateTime etc then convert it to string?

Related

How to get the value of my label? i am using c#

I have this c# form program and i want to get my text label value for some reasons, can somebody help?
I already tried this
String name = myLabel.Text
String name = myLabel.Text.ToString
but it will display none.
conn = dbHelper.getConnect();
conn.Open();
cmd = new SqlCommand("select custID from customer where name = '" + custNameLbl /*this is where i want to get the value*/ + "'", conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
custIDStorage = Convert.ToInt32(dr[0].ToString()); //this is an int
namename.Text = custIDStorage.ToString(); //this is a label
}
cmd.Dispose();
dr.Close();
conn.Close();

How can I store SQL Server query value to variable?

I want to sum all values of a column (ttl), and store result in a variable (sum), I tried some code snippets, but I didn't get any success.
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = '"+ textBox1.Text +"'",con);
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
con.Close();
}
In your code, you should close the connection after the loop, closing the connection inside the loop will cause an error:
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
}
con.Close();
Sum should return a single value, so you can simply get the value like this:
int sum = Convert.ToInt32(cmd1.ExecuteScalar());
Adding a variable directly to query makes it vulnerable for injections. Use parameters instead:
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = #id",con);
cmd1.Parameters.Add("#id", SqlDbType.VarChar).Value = textBox1.Text;

How to insert date time in database?

I'am making a time attendance system and I don't know how to store datetime in database. I really need some help with my system if anyone has any code for time attendance please share your Code a little help would do thanks..
Here is my Code:
con = newSqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(#"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = #"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}
Do not use ExecuteReader() but ExecuteNonQuery(); add query parameters, do not modify query text, technically it could be something like that:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
#"insert into Time (
TimeIn)
values (
#TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("#TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
However, table Time as it appears in the question looks very strange, hardly does it contain TimeIn field only.

C# Add value to a texbox based on the Combobox selection

We have selected a value from a combobox and need the related information in the textbox.
The following code does not work for the same.
private void itemcode_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)itemcode.SelectedItem;
SqlConnection conn3 = new SqlConnection(connString);
conn3.Open();
//For Redundency Checking Code of Supplier id.
string iname = "select Itemname from Items where Itemcode='" +
itemcode.SelectedItem.ToString() + "'";
SqlCommand cmdRedun1 = new SqlCommand(iname, conn3);
SqlDataReader dr1 = cmdRedun1.ExecuteReader();
dr1.Read();
itemname.Text = dr1["Itemname"].ToString();
dr1.Close();
}
First Check your Item Value Of Combo box , and then create your query with StringFormat
for example :
string iname = String.Format("select Itemname from Items where Itemcode='{0}'",
itemcode.SelectedItem.ToString()) ;
//-- then please check out below code :
SqlConnection SqlConn = new SqlConnection(this.ConnectionString);
SqlConn.Open();
SqlCommand SqlCmd = new SqlCommand(" Your Select....", SqlConn);
SqlCmd.CommandType = CommandType.Text;
SqlDataReader r = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
//----need this
while (r.Read())
itemname.Text = string.IsNullOrEmpty(r["Itemname"].ToString()) ?
string.Empty : r["Itemname"].ToString();
r.Close();
if (SqlConn.State != ConnectionState.Closed)
SqlConn.Close();
You can try ExecuteScalar instead of SqlDataReader.

Return value of a select statement

I want to retrieve the resulting value of a select statement into a string variable. Like this:
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
I want to place the selected treatment value into a string variable. How can I do this?
Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.
try
{
SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{
}
while(dr.Read())
{
string treatment = dr[0].ToString();
}
Or better, use a using statement for it.
using(SqlDataReader dr = cmd1.ExecuteReader())
{
while(dr.Read())
{
string treatment = dr[0].ToString();
}
}
But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-
cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());
Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.
Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
Other Way: ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
cmd1.Parameters.AddWithValue("#patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}
the answer:
String res = cmd1.ExecuteScalar();
the remark: use parametrized query to prevent sql injection
There is a lot wrong with your example code.
You have inline sql, which opens you up to sql injection in a major way.
You are using ExecuteNonQuery() which means you get no data back.
string sSQL = "SELECT treatment FROM appointment WHERE patientid = #patientId";
OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
cmd1.Parameters.AddWithValue("#patientId", text);
SqlDataReader reader = cmd1.ExecuteReader();
string returnValue;
while(reader.Read())
{
returnValue = reader[0].ToString();
}
You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();
If your SQL statement returns more than one row/column then you can use ExecuteReader().
You need to use OleDbAdapter.
string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
SqlConnection dbConnect = new SqlConnection("your SQL connection string");
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
ds = new DataSet();
sda.Fill(ds);
dbConnect.Open();
sqlcmd.ExecuteNonQuery();
dbConnect.Close();

Categories