The multi-part identifier "System.Data.DataRowView" can not be associated

1

try                 {

                if (cmbFavorecido.SelectedValue != null )
                {

                    txtID.Text = cmbFavorecido.SelectedValue.ToString();

                    cn = conexao.ConectarSqlServer();
                    cn.Open();
                    SqlCommand cmd = new SqlCommand("select CNPJ_FORNECEDOR FROM FORNECEDOR WHERE ID_FORNECEDOR =  " + txtID.Text, cn);
                    SqlDataAdapter ad = new SqlDataAdapter(cmd);

                    DataSet ds = new DataSet();
                    ad.Fill(ds, "TbFornecedor");
                    txtCnpj.Text = ds.Tables["TbFornecedor"].Rows[0].ItemArray[0].ToString();

                }
    
asked by anonymous 25.02.2016 / 12:29

1 answer

1

Try to do as follows.

 if (cmbFavorecido.SelectedValue != null)
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = myConnString;
                try
                {
                    String txtID = cmbFavorecido.SelectedValue.ToString();
                    txtID.Text = txtID;

                    //cn = conexao.ConectarSqlServer();
                    //cn.Open();

                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "select CNPJ_FORNECEDOR FROM FORNECEDOR WHERE ID_FORNECEDOR = @txtID";
                    cmd.Parameters.AddWithValue("@txtID", txtID);

                    SqlDataAdapter da = new SqlDataAdapter();
                    DataTable dt = new DataTable();

                    da.SelectCommand = cmd;
                    conn.Open();
                    da.Fill(dt);

                    txtCnpj.Text = dt.Rows[0][0];

                }
                catch (SqlException sqle)
                {
                    // MessageBox.Show("Falha ao efetuar a conexão. Erro: " + sqle);
                }
                finally
                {
                    conn.Close();
                }
            }

The one important thing in your code is that you have to be careful, that is the passing of parameters. In the way you are doing you run the risk of someone using SQL Injection , so user always Parameters.AddWithValue("@txtID", txtID); to pass parameters.

So the parameter types are appropriate for the column types, and the SQL statement is ADO.NET. In addition, it's a good practice to do validations.

    
29.02.2016 / 14:26