想要将查询结果放入c#中的文本框中

时间:2016-04-19 16:32:04

标签: c# visual-studio ms-access

我的目标是将查询结果导入文本框。我希望能够获得与我在另一个文本框中的文本框中编写的代码相关联的名称。我编写的代码仅显示查询在文本框中不是它的结果。 这是代码:

private void btnassociar_Click(object sender, EventArgs e)
{
    string codigo,pesquisanome;

    codigo = txtcodigo.Text;
    pesquisanome = "select nome from produto where cod_produto like '%" + codigo + "%'";
    txtnomeassociado.Text = pesquisanome;

}

1 个答案:

答案 0 :(得分:1)

这是你可以做的一个例子。您必须执行查询,并读取结果。

string queryString = "select nome from produto where cod_produto like '%" + codigo + "%'";
public string connectionString= "Data Source=Kadfas;Initial Catalog=PowerBI;Integrated Security=True";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
           // get the results here
           reader.GetString(0); // result of the first field.
        }
    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
    }
}