简体   繁体   中英

how to get all the column value in C# from database table

public void doTry()
        {
            db.ConnectionCheck();
            string sqlUname = "";
            string oracleUname = "";
            string usertesting = "select * from nayatable";
            db.cmd = new SqlCommand(usertesting, db.DBconnect);
            SqlDataReader myReader = db.cmd.ExecuteReader();
            if (myReader.Read())
            {
                sqlUname = myReader["USERNAME"].ToString();
                //MessageBox.Show(uname);
                textBox1.Text = sqlUname;
            }
    }

It only gives first row second value but I need all the column in available in database.

There are numerous options here either you can go for DataTable as Ehsan said or you can use List to collect all the data. Something Like this:

public class dbLogin
{
   public string userName{get;set;}
}

public void doTry()
    {
        db.ConnectionCheck();
        string sqlUname = "";
        string oracleUname = "";
        string usertesting = "select * from nayatable";
        db.cmd = new SqlCommand(usertesting, db.DBconnect);
        SqlDataReader myReader = db.cmd.ExecuteReader();

List<dbLogin> dbData=new List<dbLogin>();


 if (myReader.Read())
        {
            dbLogin _dbLogin=new dbLogin();
            _dbLogin.userName = myReader["USERNAME"].ToString();
            textBox1.Text = sqlUname;
            dbData.Add(_dbLogin);
        }
}

If you want to get all the values, you have to loop :

        ...
        // Keep Sql Readable
        // Do not fetch unwanted columns - * 
        string userTesting = 
          @"select UserName 
              from NayaTable";

        // Wrap IDisposable into using
        using (db.cmd = new SqlCommand(userTesting, db.DBconnect)) {
          // Wrap IDisposable into using
          using(SqlDataReader myReader = db.cmd.ExecuteReader()) {
            // we are going to build one string from many records
            StringBuilder sb = new StringBuilder();

            // Here, we have to loop and aggregate / collect all the records
            while (myReader.Read()) {
              if (sb.Length > 0)
                sb.Append(", "); // delimiter 

              sb.Append(Convert.ToString(myReader["USERNAME"])); 
            }

            // Here you'll get usernames like "Sam, John, Mary" 
            textBox1.Text = sb.ToString(); 
          }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM