Happy Bee
Happy Bee

Reputation: 71

How to retrieve data from postgres to textbox in c#.net

I want to retrieve data from postgres db into textbox in C# without using grid.

Here is the running successful code by using grid which I had tried:

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();

I get error when build when I want to retrieve it into textbox: "cannot apply indexing with [] to an expression of type 'NpgsqlDataAdapter'"

Here is my block of code:

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();

Upvotes: 1

Views: 1454

Answers (2)

Mowazzem Hosen
Mowazzem Hosen

Reputation: 507

try this . .

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();

Upvotes: 0

Olivier Depriester
Olivier Depriester

Reputation: 1625

A DataAdapter is not an array of rows you can loop into.
Look at your first code block : you must fill a DataTable from your adapter and then read through the Rows property of 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();
}

You could also do this :

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

And please, remove the cmd.ExecuteNonQuery(); line, it is useless here

Upvotes: 1

Related Questions