Skip to content
Advertisement

How to retrieve multiple column from SQL database?

I’m trying to get two column details like this way:

    public string GetData()
    {

        using (SqlConnection con = new SqlConnection(this.Connection))
        {
            con.Open();

            SqlCommand command = new SqlCommand("Select TITTLE,VALUE from T_PROJECTS ", con);



            // int result = command.ExecuteNonQuery();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                reader.Read();
                return reader["TITTLE,VALUE"]?.ToString();
            }

        }
    }

How can I do this?

Advertisement

Answer

You need to have a custom class of columns that you want to retrieve, for example,

 public class Project
        {
          public int Title { get; set; }
          public string Value { get; set; }         
        }

and then like this,

 public Project GetData()
    {

        using (SqlConnection con = new SqlConnection(this.Connection))
        {
            con.Open();
            SqlCommand command = new SqlCommand("Select TITTLE,VALUE from T_PROJECTS ", con);
            Project proObj = new Project();            
            using (SqlDataReader reader = command.ExecuteReader())
            {
                reader.Read();
                proObj.Title = reader["TITTLE"].ToString();
                proObj.Value = reader["VALUE"].ToString();
            }

        }
     return proObj;
    }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement