首页 > 解决方案 > 如何在 c#.net 中从 postgres 检索数据到文本框

问题描述

我想在不使用网格的情况下将 postgres db 中的数据检索到 C# 中的文本框中。

这是使用我尝试过的网格运行成功的代码:

connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM student_folio";
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
connection.Close();
GridView1.DataSource = dt;
GridView1.DataBind();

当我想将它检索到文本框中时,我在构建时遇到错误:“无法使用 [] 将索引应用于‘NpgsqlDataAdapter’类型的表达式”

这是我的代码块:

connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = ("SELECT f_name FROM student_folio WHERE id = 1");
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);

txtFname.Text = da["f_name"].ToString();
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();

标签: c#.netpostgresql

解决方案


ADataAdapter不是您可以循环进入的行数组。
查看您的第一个代码块:您必须DataTable从适配器中填充 a ,然后通读Rowsthis 的属性DataTable

NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
  txtFname.Text = dt.Rows[0]["f_name"].ToString();
}

你也可以这样做:

foreach (System.Data.DataRow row  in dt.Rows)
{
  txtFname.Text = row["f_name"].ToString();
}

并且请删除该cmd.ExecuteNonQuery();行,它在这里没用


推荐阅读