user3500993
user3500993

Reputation: 25

Conversion failed when converting the varchar value 'System.Data.DataRowView' to data type int

I always get the following error once I retrieved records with integer data type from my database using my combobox:

Conversion failed when converting the varchar value 'System.Data.DataRowView' to data type int.

It works when I replace my query and retrieve records that has varchar data type.

Can someone please help me how to modify my code to get the expected output?

Here is my code:

public void fillSupplier()
{
    SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
    conn.Open();
    string query = "Select supID from Supplier";
    SqlCommand cmd= new SqlCommand(query,conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    if (dt.Rows.Count > 0) {
        cmbSupp.DataSource = dt;
        cmbSupp.DisplayMember = "supID";
        cmbSupp.ValueMember = "supID";
    }
}

private void cmbSupp_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
    conn.Open();
    this.Refresh();
    string query = "Select * from Supplier where supID='"+cmbSupp.Text+"'";
    SqlCommand cmd = new SqlCommand(query,conn);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read()) { 
        tbsName.Text = dr["supName"].ToString();
        tbsContact.Text = dr["supLocation"].ToString();
        tbsLoc.Text = dr["supContact"].ToString();
    }
}

Upvotes: 0

Views: 9176

Answers (1)

Grant Winney
Grant Winney

Reputation: 66449

Replace it with this (removed the single apostrophes, which indicate a string literal):

string query = "Select * from Supplier where supID = " + cmbSupp.Text;

Also, look into parameterizing your query. You'll be far less likely to run into issues like this, especially when the query you're executing has many parameters.

string query = "Select * from Supplier where supID = @supID";
...
cmd.Parameters.AddWithValue("@supID", int.Parse(cmbSupp.Text));

Here's some good reading material, with examples.

Upvotes: 1

Related Questions