如何在 c#.net 中从 postgres 检索数据到文本框

我想在不使用网格的情况下将 postgres 数据库中的数据检索到 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();


慕桂英4014372
浏览 53回答 2
2回答

慕姐8265434

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();行,它在这里没有用

慕沐林林

尝试这个 。。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();
打开App,查看更多内容
随时随地看视频慕课网APP