c# - 如何在 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();
解决方案
ADataAdapter
不是您可以循环进入的行数组。
查看您的第一个代码块:您必须DataTable
从适配器中填充 a ,然后通读Rows
this 的属性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();
行,它在这里没用
推荐阅读
- .net - 如何在 .NET Core 托管服务中的同一项目下安装多个服务
- c# - 开发需要依赖 dll 的动态 365 插件的最佳方法是什么?
- visual-studio-code - Code Runner 不适用于 VsCode 中的 Python
- spring - @PostConstruct:嵌套依赖项为空
- html - 当引导下拉菜单打开时如何切换按钮图标
- javascript - 无法对齐 svg 和
与 display:inline-block 在同一行?
- python - 将参数添加到应用于 pd.df 的 eval 函数
- javascript - Nodemon 安装不正确
- java - 如何计算(O)N中的最高和
- mysql - 迁移文件必须在 Sequelize 中吗?