简体   繁体   中英

How to store values got from datatable into a string?

I want to get Data table values and save them in a single string, where dt.rows.Count is more that 0. 在此处输入图片说明 I want get menu_name , menu_Quantity and store them into a single string where email=ariffnaj@gmail.com . If this is possible, can you show how to do it, this code only save into string at first column only

SqlConnection conn = new SqlConnection(ConfigurationManager.
                    ConnectionStrings["connectionString"].ConnectionString);
 string cartsql = "SELECT menu_name,menu_price,menu_quantity FROM cart where email=@email";
        SqlCommand cmd1 = new SqlCommand(cartsql, conn);
        cmd1.Parameters.AddWithValue("@email", Session["email"].ToString());
        SqlDataAdapter sda = new SqlDataAdapter(cmd1);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        if (dt.Rows.Count > 0)
        {

            foreach (DataRow dtRow in dt.Rows)
            {
                string menuname = dtRow["menu_name"].ToString();
                string menuprice = dtRow["menu_price"].ToString();
                string menuquantity = dtRow["menu_quantity"].ToString();

            }

        }

My solution uses a SqlDataReader instead of SqlDataAdapter and DataTable . This is easier, if you only want to retrieve some values. To build the string I use a StringBuilder , as it manages the resources better than string concatenation would.

public string GetCartStringForEMail(string email)
{
    const string sql = "SELECT menu_name, menu_quantity FROM cart WHERE email=@email";

    string connectionString =
        ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, conn)) {
        var sb = new StringBuilder();
        cmd.Parameters.AddWithValue("@email", email);
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read()) {
            sb.Append(reader.GetString(0))
                .Append(", ")
                .AppendLine(reader.GetInt32(1).ToString());
        }
        return sb.ToString();
    }
}

Note that the using-statements automatically close the connection and release the resources.

You can try coalesce function:

DECLARE @str nvarchar(MAX)
SELECT @str = (COALESCE(@str + ';', '') + CONCAT('Menu:', menu_name, ', Quantity:', menu_quantity)) 
FROM cart WHERE email=@email
SELECT @str as output

And then use: String str = cmd1.ExecuteScalar().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