1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

By the way, another solution would be to use a DataReader instead of DataAdapter + DataTable. It is less heavy to achieve something like this. I guess a NpgsqlDataReader class must also exist
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.