Input string was not in a correct format - c#

public int getcid(string UserName)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
int js;
string query = "select Username from register_tab where Email='" + UserName + "' ";
sqlda = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
sqlda.Fill(ds);
js = Convert.ToInt32(ds.Tables[0].Rows[0]["Username"].ToString());
return (js);

Change your method to this and check it out:
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string js;
string query= "select Username from register_tab where Email= #username";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#username",SqlDbType.VarChar, 50).Value =
UserName;
using(SqlDataReader reader= cmd.ExecuteReader())
{
while (reader.Read())
{
js= reader["Username"].ToString();
}
}
con.Close();
return js;
Also why do you set your UserName to Email Column in your query?
And why do you use DataSet if you only want to return int?
UPDATE: no need to convert to int.

Related

Error to convert varchar to float using c#

I have a problem , i'm trying to do operations between values recorded(type float) in table of data , the problem is when i try to update value(result of the operation in textbox) in datable using combobox after maintaining opération , it shows me error (System.Data.SqlClient.SqlException: 'Error converting data type varchar to float.'), So how can i resolve that !help please
This is a part a of my code in which the error exists
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Table_com where Variable='" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
MessageBox.Show("Variable mise à jour avec succés");
}
You cannot use float integer etc. values like text field as:
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
and your code really risky, you may use parameters like this, dont use string and convert your value to float :
static void Main(string[] args)
{
var ConnectionString = "YOUR CONNECTION STRING";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
String query = "UPDATE Table_com SET Contents=#contents WHERE Variable=#variable";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = Convert.ToDouble(textBox6.Text);
cmd.Parameters.Add("#variable", SqlDbType.NVarChar).Value = comboBox5.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
this is what i tried refering to wikiCan answer
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-VEFPLGG\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String query = "UPDATE Table_com SET Contents=#contents ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = textBox6.Text;
//cmd.Parameters.Add("#variable", SqlDbType.Float).Value = Convert.ToDouble(comboBox5.Text);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

How to work with null incoming from database

I'm getting this error
This method or property cannot be called on Null values
on this line id = rd.GetString(0);. How to solve it?
public string MaxId()
{
string id = "";
con.Open();
string sql = "SELECT MAX(id) FROM Customer";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read()){
id = rd.GetString(0);
}
con.Close();
return id;
}
add this
!rd.IsDBNull(0)
before
id = rd.GetString(0);
So, your code would look like
public string MaxId()
{
string id = "";
con.Open();
string sql = "SELECT MAX(id) FROM Customer";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
if(!rd.IsDBNull(0))
id = rd.GetString(0);
}
con.Close();
return id;

How do I add SQL auth to a C# forms app?

I need to be able to verify a username and password against a sql server and I need code for a C# forms application.
I have it setup with 2 textboxes (1 user and 1 pass) and then I have a login button.
SqlConnection UGIcon = new SqlConnection();
UGIcon.ConnectionString = "Data Source=HP-PC//localhost;Initial Catalog=UGI;Integrated Security=True";
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword FROM LoginDetails WHERE stUsername='" + textBox11.Text + "' and stPassword='" + textBox12.Text + "'", UGIcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if ( dt.Rows.Count > 0)
{
MessageBox.Show("Login Success!!");
cmd = new SqlCommand("SELECT stRole from LoginDetails where stUsername=#stUsername", UGIcon);
cmd.Parameters.AddWithValue("#stUsername",userText);
string role = cmd.ExecuteScalar().ToString();
MessageBox.Show(role);
UGIcon.Close();
}
else
{
MessageBox.Show("Access Denied!!");
UGIcon.Close();
}
I'm a real believer in using the "using" statements. You can also save yourself a 2nd query by asking for the stRole variable in the original query. The using blocks will automatically dispose of the objects, so when execution leaves this area, the objects will automatically be cleaned up.
using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True"))
{
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
string role = rdr["stRole"].ToString();
MessageBox.Show(role);
}
}
else
{
MessageBox.Show("Access Denied!!");
}
}
}
Pls check this code
SqlConnection thisConnection = new
SqlConnection(#"Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "Select count(*) from UserDetails
WHere UserName = "+txtUsername.text.trim().toLower() + " and Password = " +txtPassword.text.trim().toLower();
Object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers = {0}", countResult);
thisConnection.Close();

insert data to table based on another table C#

I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.

Categories

Resources