In the code below, i just want to fill my textbox based on the selected combo box changed. but i get the following error.
'Conversion failed when converting the varchar value 'System.Data.DataRowViewConvert.ToString()' to data type int.'
i'd appreciate it if you help me.
SqlConnection objConnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
private void comboBox1_Click(object sender, EventArgs e)
{
string query = "SELECT *FROM TutorTable";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
DataTable dt = new DataTable();
SDA.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tid";
objConnection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Why are you using the Convert.ToString() in this piece of code:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'"
I think the correct way wolud be:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "'"
But consider using a store procedure to prevent sql injection or using an ORM.
I think that comboBox1.Text
is already returning a string value. So if that, it is not necessary to put the Convert.ToString(comboBox.Text)
, just put comboBox1.Text
According to documentation, the Text property is a string https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text(v=vs.110).aspx