[英]How to retrieve data from postgres to textbox in c#.net
我想在不使用网格的情况下将数据从 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();
DataAdapter
不是可以循环进入的行数组。
查看您的第一个代码块:您必须从您的适配器填充一个DataTable
,然后通读这个DataTable
的Rows
属性。
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();
行,这里没用
尝试这个 。 .
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlDataReader dr=null;
cmd.Connection = connection;
cmd.CommandText = ("SELECT f_name FROM student_folio WHERE id = 1");
cmd.CommandType = CommandType.Text;
dr=cmd.ExecuteReader();
while(dr.HasRows)
{
while(dr.Read())
{
txtFname.Text = da["f_name"].ToString();
}
}
connection.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.